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>
usingnamespace 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.
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!
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;
}