In this code:
string question;
cout<<"Enter Your Question: "<<endl;
cin>>question; // <-- WRONG
getline(cin, question);
cout<<question<<endl;
ofstream g("question.txt",ios::app);
g<<question<<endl;
cin >> question
is reading in only the 1st word of the user's input into question
, and then getline(cin, question)
is reading in the rest of the input into question
again, overwriting its current value. This is why you are losing the beginning characters of the input.
You need to get rid of the >>
here, eg:
string question;
cout<<"Enter Your Question: "<<endl;
getline(cin, question); // <-- USE BY ITSELF!
cout<<question<<endl;
ofstream g("question.txt",ios::app);
g<<question<<endl;
However, you claim you already tried this and it doesn't work at all. That means the cin
stream is not in the state you are expecting to begin with, thus std::getline()
is ignoring the input you want.
For instance, if you had used cin >> ...
to read in an earlier input, and the user had pressed Enter after that input, then there would be a '\n'
character in cin
's input buffer. If you do not read in that '\n'
character beforehand, std::getline()
will not work in this code.
For example: let's say you prompt the user for a number, and then they press Enter. And then you prompt for the question. Thus:
cin >> number;
...
cin >> question;
getline(cin, question)
Would work as expected (just not with the result you want). cin >> number
would read in the number, leaving the '\n'
in the input buffer. Then cin >> question
would skip the '\n'
as leading whitespace, and read in the 1st word of the question. Then getline(cin, question)
would read in the rest of the question up to the next '\n'
.
Whereas:
cin >> number;
...
getline(cin, question)
Would not work as expected. cin >> number
would read in the number, leaving the '\n'
in the input buffer. Then getline(cin, question)
would stop reading immediately when it reads in the '\n'
, leaving the whole question in the input buffer.
That would explain the behavior you are seeing.
See Why does std::getline() skip input after a formatted extraction?. To solve this, you would need to do this instead:
cin >> number;
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ADD THIS!
...
getline(cin, question);
Now std::getline()
will read in the whole question correctly, as expected.