-
getline instead of cin>>
i've got this code:
Code:
cout <<"insert a string: ";
std::string s;
cin>>s;
when i enter a string with spaces cin only records in s til the first space.
example:
insert a string: Hello world!
only hello is stored in s.
I've heard that the getline functions solves this. I read Eckel's thinking in c++ vol 2 but i couldn't understand how to use it. Would you mind telling me?
thanls!!
-
For example:
Code:
string str1;
while(str1.empty())
{
cout << "Enter a string: ";
getline(cin, str1);
cout << endl;
}
Hope that helps :)
-
it didn't work
I ran the debugger and after getline(cin, str1); nothing is stored in str1
:(
-
Code:
#include <iostream>
using namespace std;
int main()
{
string str1;
while(str1.empty())
{
cout << "Enter a string: ";
getline(cin, str1);
cout << endl;
}
cout << str1;
cin.get();
return(0);
}
Does that work for you? It does for me.
-
thanks!! the while (str1.empty()) did it
-
you can also use the gets function, which I believe is in the string.h library. What gets does is get input from STDIN until a \n is encountered.
void main()
{
char buf[128];
gets(buf);
blah blah blah.......
}
-