You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++统计字符串空格数程序报错:int无法转string如何修复?

解决C++统计字符串空格数量的编译错误

错误核心原因

函数count_spaces声明返回std::string类型,但实际要返回的是统计得到的空格整数数量,类型不匹配直接触发编译错误。
另外还有两个隐藏问题:

  • 变量spaces未初始化,直接执行spaces +=1会导致未定义行为(程序可能输出随机值)。
  • 用substr(i, 1) == " "判断空格的方式效率较低,没必要每次生成子字符串。

修复方案

  1. 修正返回值类型:把函数的返回类型从string改为int,和返回的spaces变量类型一致。
  2. 初始化变量:将int spaces;改为int spaces = 0;,避免未定义行为。
  3. 优化判断逻辑:直接通过hi[i] == ' '判断当前字符是否为空格,无需生成子串。

修复后的完整代码

#include <iostream>
#include <string>
using namespace std;

/**
   Gets the number of spaces in a string.
   @param str any string
   @return the number of spaces in str
*/

int count_spaces(string hi) {
   int spaces = 0;
   for (int i = 0; i < hi.length(); i++) {
      if (hi[i] == ' ')
          spaces += 1;
   }
   return spaces;
}

int main()
{
   string str;
   getline(cin, str);
   cout << count_spaces(str) << endl;
   return 0;
}

更简洁的实现(用标准库函数)

可以直接使用<algorithm>头文件中的count函数,一行完成统计:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int count_spaces(string hi) {
   return count(hi.begin(), hi.end(), ' ');
}

int main()
{
   string str;
   getline(cin, str);
   cout << count_spaces(str) << endl;
   return 0;
}

内容的提问来源于stack exchange,提问作者tluths

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 02:02:21