simple string size

#include <iostream>

using namespace std;

int main()
{
string str;
cout<<"string";
cin >> str;
cout << "The size of str is " << str.size() << " characters.\n";

return 0;
}
should be very simple right well everything works except if the user enters a space it stops. EX "Dog Toy" should be 7 but I keep getting three. Please help
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>
using namespace std;

int main()
  {
  string str;
  cout << "string: ";
  getline( cin, str );
  cout << "The size of your string is " << str.length() << " characters.\n";
  return 0;
  }

Good luck!
1
2
3
4
5
        cout<< "Character Counter"<<endl<<endl;
        cout << "string: ";
        getline( cin, userinput );

        cout<<"Total Number of Charactars= " << userinput.length();

I have the #include <string> at the top. See anything wrong its like I have put no cin it just never wait on user input it moves on. BTW userinput is a sting i declared. Mine looks exactly like your except names and output
This works fine for me...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

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

int main()
{
	string name = " ";
	cout << "\n\nEnter name : ";
	getline(cin, name);
	cout << name.size() << endl << endl;
return 0;
}
/*output

mypc@myPc:~/cpp$g++ something.cpp
mypc@myPc:~/cpp$ ./a.out something.cpp


Enter name : Jon Mark Smith
14
*/
Last edited on
It works for me to but when I changed it to what I had all the sudden it stops working
cin stops reading at a white space, {" ", ' ', \n, \t,...} any type of white space.
if you need to read something that could have spaces (string) use getline(cin, var);
and if your reading in a character array use cin.getline(var, sizeof(var));
Last edited on
I understand what all of it does the problem is it acting like I haven't even put the getline in there it just skips it and moves on.
Post all your code.
Topic archived. No new replies allowed.