如果字符串中有空格,String.size() 将返回错误的数字
我正在尝试编写一个返回字符串中字符数的程序。当我编写程序时,我注意到字符串类中存在一个错误。
假设我的程序是这样的:
#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;
}
如果我的输入是测试字符串,我应该看到数字11作为输出。
但是,我得到的输出是这样的:
Number of characters: 4
当字符串中有空格时, size() 方法似乎不起作用。
我的问题是,是否有另一种方法来获取字符串中的字符数?我尝试了 length() 方法,但结果是相同的。
I'm trying to write a program that returns the number of characters in a string. As I was writing my program, I've noticed that there's a bug in the string class.
Say my program is this:
#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;
}
If my input is Test String, I should see the number 11 as the output.
However, the output I get is this:
Number of characters: 4
It seems like the size() method does not work when there is space in the string.
My question is, is there another way to get the number of characters in a string? I tried length() method but the result was the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
那是因为您
只能读取第一个空白字符。
如果你想获取整行,请使用以下代码:
That's because your
only reads up to the first whitespace character.
If you want to get the a whole line, use the following code:
这不是一个错误,更具体地说,实际上与字符串类无关。
它与 istream 类 (cin) 有关。 cin 的运算符>>执行“格式化输入”,也就是说,输入由空格分隔。按回车键后,将“Test”读入字符串中,将“String”留在输入缓冲区中。事实上,“测试”有四个字符长。
考虑使用 std::getline 或 istream::getline 来以更多控制读取整行输入。请务必仔细阅读这些方法的文档,因为它们对于输入流中剩余的内容有不同的行为,如果与 oeprator>> 混合在一起,可能会导致您意想不到的结果。用法。
This is not a bug, and more particularly, actually has nothing to do with the string class.
It has to do with the istream class (cin). cin's operator>> performs "formatted input," which is to say, input delimited by whitespace. After you hit enter, you read out "Test" into a string, leaving "String" in the input buffer. "Test" is, in fact, four characters long.
Consider using std::getline or istream::getline to read entire lines of input with more control. Be sure to read the documentation for these methods carefully, as they have different behavior with respect to what is left in the input stream which can then cause results you may not expect if mixed together with oeprator>> usage.
这是
cin>>意义的结果。 input
,当发现任何空格时停止读取。如果您想继续阅读直到一行末尾,请尝试getline
。
This is a result of the meaning of
cin >> input
, which stops reading when any whitespace is found. If you want to keep reading until the end of a line, trygetline
.正确获取输入后,您可以使用 strlen(string_name) 获取字符串或字符指针(char*)(包括空格)的长度,这将返回长度。
After taking input correctly, you can get the length of the string or char pointer(char*)(including whitespaces) by using strlen(string_name), this will return the length.