0

I wanted to clear some doubt regarding the function

cin.ignore(1,'\n');   

code:

char x[80];      
cin>>x;       
cin.ignore(1,'\n');      

If user input the word: paul Smith
does the program looks for the first space in the word and ignores/delete the rest of the characters?
Hence the program takes paul only and discards Smith?
Am I right?
I'm getting confused! Please explain in really simple words because I cannot understand the explanation on google regarding this issue.

Farhaan
  • 63
  • 1
  • 1
  • 3

2 Answers2

0
cin.ignore(1,'\n');

is not very useful. It will ignore only one character.

cin.ignore(100,'\n');

will ignore up to 100 characters but will stop after it encounters a '\n'.

In your case,

cin>>x;       

will read paul into x. The line

cin.ignore(1,'\n');

will consume the space after paul. Hence, Smith will be left on the input stream.

Hence the program takes paul only and discards Smith?

No. I hope that is clear from the above.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0
cin >> x;

Since x is a string or char array, this reads one word (everything up to the first whitespace character) from the input, and stores it in x.

cin.ignore(1, '\n');

reads and ignores one character from the input. It won't read the whole rest of the line. More generally:

cin.ignore(n, delim);

reads and ignores characters until it has either read n characters or reached a character equal to delim. If you want to ignore until the end of the line, no matter how many characters that is, do:

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Barmar
  • 741,623
  • 53
  • 500
  • 612