-
May 1st, 2004, 03:46 PM
#1
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!!
-
May 1st, 2004, 05:59 PM
#2
For example:
Code:
string str1;
while(str1.empty())
{
cout << "Enter a string: ";
getline(cin, str1);
cout << endl;
}
Hope that helps
-
May 1st, 2004, 06:27 PM
#3
it didn't work
I ran the debugger and after getline(cin, str1); nothing is stored in str1
-
May 1st, 2004, 07:09 PM
#4
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.
-
May 2nd, 2004, 09:18 PM
#5
thanks!! the while (str1.empty()) did it
-
May 3rd, 2004, 11:58 AM
#6
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.......
}
-
May 3rd, 2004, 12:09 PM
#7
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|