我正在尝试编写一个返回字符串中字符数的程序.当我编写程序时,我注意到字符串类中存在错误.
说我的程序是这样的:
#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;
}
Run Code Online (Sandbox Code Playgroud)
如果我的输入是测试字符串,我应该看到数字11作为输出.
但是,我得到的输出是这样的:
Number of characters: 4
Run Code Online (Sandbox Code Playgroud)
当字符串中有空格时,似乎size()方法不起作用.
我的问题是,是否有另一种方法来获取字符串中的字符数?我尝试了length()方法,但结果是一样的.