C++统计字符串空格数程序报错:int无法转string如何修复?
解决C++统计字符串空格数量的编译错误
错误核心原因
函数count_spaces声明返回std::string类型,但实际要返回的是统计得到的空格整数数量,类型不匹配直接触发编译错误。
另外还有两个隐藏问题:
- 变量
spaces未初始化,直接执行spaces +=1会导致未定义行为(程序可能输出随机值)。 - 用
substr(i, 1) == " "判断空格的方式效率较低,没必要每次生成子字符串。
修复方案
- 修正返回值类型:把函数的返回类型从
string改为int,和返回的spaces变量类型一致。 - 初始化变量:将
int spaces;改为int spaces = 0;,避免未定义行为。 - 优化判断逻辑:直接通过
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
相关产品推荐
相关产品推荐

