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?
That's because
cinstops at whitespace. If you want to read all your words, you'll need to loop:Or if you want them all at once, you'll need to use
getline: