string.length() stops after first word

183 Views Asked by At

I'm trying to find out the length of a string. This works and outputs 14:

#include <iostream>
#include <string>
using namespace std;

int main(){
     string str = "this is sparta";
     cout << str.length() << endl;
}

However this fails:

#include <iostream>
#include <string>
using namespace std;

int main(){
     string str;
     cin >> str;
     cout << str.length() << endl;
}

When I type in the sentence this is sparta and hit return I get 4 as length.

What am I doing wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

That's because cin stops at whitespace. If you want to read all your words, you'll need to loop:

int main() {
    string str;
    while (cin >> str) {
        cout << str << " --> " << str.length() << endl;
    }
}

Or if you want them all at once, you'll need to use getline:

int main() {
    string str;
    while (getline(cin, str)) {
        cout << str << " --> " << str.length() << endl;
    }
}