我正在尝试编写一个返回字符串中字符数的程序。在编写程序时,我注意到字符串类中有一个错误。
说我的程序是这样的:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string input;
cout << "Input string: ";
cin >> input
cout << "Number of characters: " << input.size() << endl;
return 0;
}
如果我的输入是 Test String ,我应该看到数字 11 作为输出。
但是,我得到的输出是这样的:
Number of characters: 4
当字符串中有空格时,size() 方法似乎不起作用。
我的问题是,是否有另一种方法来获取字符串中的字符数?我尝试了 length() 方法,但结果是一样的。
原文由 pandascope 发布,翻译遵循 CC BY-SA 4.0 许可协议
那是因为你的
最多只能读取第一个空白字符。如果要获取整行,请使用以下代码: