getline

Hello,
I want to save a string with " " so I cant use the normal cin>>variable; right?
But If i try using getline(cin,variable); more then once I succeed only the first time in the loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string> 
using namespace std; 

int main() 
{
 string a; int b;
 while (b!=1) 
       {
        cout<<"Text? "; getline(cin,a);
        cout<<"\nb? "; cin>>b; 
        cout<<endl<<a<<endl;
       }
 return 0;     
}

this getline(cin,variable); is kind of a weird notation. I assume it is some function of inputstream and variable? what other 1st argument could I use there?

also I have seend the notation cin.getline(...); how does that work what are the parameters? I didnt get it to work.

Last edited on
cin.getline() is by my knowing not C++ ?
anyways, when I was starting out I had the exact same problem.
the command std::cin leaves a whitespace buffer, i think.
Then, when you call getline again, it just gets the whitespace from the buffer and not what you entered!
So a solution would be to make a string buffer; and read with getline the remaining buffer in after you used cin!

I hope I was clear enough :p
Do you mean that the second run of the loop, the variable seems to be empty?

Try using cin.ignore() after the getline call and b input.

I've had a similar problem before too:
http://www.cplusplus.com/forum/beginner/29274/
Last edited on
xander333 wrote:
cin.getline() is by my knowing not C++ ?

http://www.cplusplus.com/reference/iostream/istream/getline/

It only works with C strings, though.

Halozination wrote:
this getline(cin,variable); is kind of a weird notation

It's as weird as foo(a, b). It's just a normal function call, with two arguments being passed: an input stream and a std::string. http://www.cplusplus.com/reference/string/getline/

But If i try using getline(cin,variable); more then once I succeed only the first time in the loop

The problem is cin >> b; leaves a newline in the stream. cin.ignore() will extract it and ignore it: http://www.cplusplus.com/reference/iostream/istream/ignore/
Last edited on
the command std::cin leaves a whitespace buffer, i think.
The problem is cin >> b; leaves a newline in the stream.

The way I have been thinking about it is what I put in streams in direction of the >> towards the variable. And I still dont understand what "newline in stream" for example means.

Anyway both solutions you worked, thank you.
1
2
3
4
5
6
7
8
while (b!=1) 
       {
        cout<<"Text? "; getline(cin,a);
        cout<<"\nb? "; cin>>b; 
         
        //(string buffer; getline(cin,buffer);) or cin.ignore(); 
        cout<<endl<<a<<endl;
       }
Last edited on
gets() is very unsafe and should never be used: http://en.wikipedia.org/wiki/Gets
Topic archived. No new replies allowed.