different within getchar(); and while (getchar() != '\n') ;

Jan 16, 2011 at 2:47am
Different between this
Why we should replace
getchar();

with
while (getchar() != '\n') ;

please let me know their meaning

Thank you
Last edited on Jan 16, 2011 at 4:09am
Jan 16, 2011 at 4:44am
For what purpose?
getchar returns a character from the standard input.
Jan 16, 2011 at 4:54am
I'm guessing that that line is at the end of a program?

As I can test there is no difference between the two lines as both wait for '\n' to get input (that's the user hitting enter.) If you change the '\n' to something like '9' or ';' you can keep it open until you get that specific character.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <cstdio> // for getchar();
#include <iostream>

using namespace std;

int main()
{
  cout << "Closing!" << endl;

  getchar(); // Waits for '\n' (user hitting enter)
  while(getchar() != '\n'); // Waits for '\n'
  while(getchar() != '9'); // Waits for user to enter '9' and enter.

  return 0;
}


Reference on getchar(): http://www.cplusplus.com/reference/clibrary/cstdio/getchar/
Topic archived. No new replies allowed.