C++ using cin.ignore() to grab only first char

wxjunkie

Senior member
Nov 6, 2000
409
0
0
Does anyone know the parameters for cin.ignore() so that I can only accept the first character into a char and ignore everything after?
 

Vadatajs

Diamond Member
Aug 28, 2001
3,475
0
0
try cin.get(char) where char is the name of a char variable. It gets one character from the input stream.
 

ant80

Senior member
Dec 4, 2001
411
0
0
Parameters of cin.ignore() are an integer, a number of spaces to ignore. In addition, you may have a delimiting character. Dont use ignore for reading 1 character. As Vadatajs said, use cin.get() or do

char ch;
cin>>ch;

This will get u one character. I personally preffer the latter approach for the sake of effeciency.
 

Ynog

Golden Member
Oct 9, 2002
1,782
1
0
Vadatajs and Ant80 the only problems with those ways is if there is more in the buffer it will not be ignored.

If he wxjunkie wants to input one line then that is a good way to do it. However if he needs to input more than
one string from the command line, or file, the remaining buffer will still be there and can be incorrectly read into
another buffer.

Two simple ways to do it would be to declare a character array and do a getline and read the entire line and just
pick off the front char from the array. Or something similer to that.

Or you can pick off the front characters as you have suggested and do a cin.ignore(1000,'\n') afterwards.
This should clear out the buffer for you so you don't have anything you don't want.

Hope this helps