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

c++, size, string

Solution

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);

Problem

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.

Original source