开发者

String.size() returns incorrect number if there is space in the string

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.


That's because your

cin >> input; 

only reads up to the first whitespace character. If you want to get the a whole line, use the following code:

std::string s;
std::getline(std::cin, s);


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.


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, try getline.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜