0

Despite entering 'y' the code isn't accepting more input. This much part is not yielding the required result.

Code block:

char ch='y';
of.open("FileHandling.txt", ios::app);          //opening file.
while(ch=='y')
{
  cout<<"\n\n\t\tEnter contents in the file : \n\n\t\t";
  getline(cin, content);
  of<<content;
  cout<<"\n\n\t\tWish to write more ( y / n ) ? : ";
  cin>>ch;
}
of.close();         //closing file.

Program should take in input as per the wish of user which is not being done. Then it should display the contents of the file. It is displaying the contents.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
farz
  • 13
  • 2
  • Read about [when to use cin.ignore()](https://stackoverflow.com/questions/25475384/when-and-why-do-i-need-to-use-cin-ignore-in-c). – rafix07 Jul 21 '19 at 13:35
  • Mixing line-oriented input (`getline()`) and formatted input (`cin >> ch`) on the same stream results in strange interactions, because the different approaches handle newlines and other whitespace differently. For example, when reading `cin >> ch` and the user has entered `Y` followed by a newline, and followed by `Hello`, then `ch` will have the value `Y`, the newline will cause `getline` to return with no content, and the `H` will be read by `cin >> ch`, so the rest of the line will be discarded. Simple solution: use one approach or the other to read ALL input from `cin`. Don't mix them. – Peter Jul 21 '19 at 14:00

2 Answers2

0

While entering single character by

cin >> ch;

new line character is put in cin stream (after y or n was entered, you also click Enter to go new line). Then in loop getline is executed which reads all characters until new line occurs. And this function works properly, it reads 0 bytes - such number of characters precede entered new line character.

To ignore this new line and read content use cin.ignore():

cin>>ch;
cin.ignore();
rafix07
  • 20,001
  • 3
  • 20
  • 33
0

You need to eat the newline character. One way to do this is by using std::istream::ignore, like this:

cout<<"\n\n\t\tWish to write more ( y / n ) ? : ";
cin>>ch;
cin.ignore();

Think of what you, the user (not the programmer), do when you are asked "Wish to write more ( y / n ) ? :".

You type 'y' for example, and then press Enter. That Enter is the newline character, which will await in the STDIN buffer to be consumed.

That newline character gets consumed by getline(), that's why you are not prompted to input content, because the function call is already terminated (since it did its job, it read a string from the STDIN buffer).

By ignoring the newline character, the getline() function will be called and wait for the user to type something...

gsamaras
  • 71,951
  • 46
  • 188
  • 305