Akram Lazkanee
Akram Lazkanee

Reputation: 411

How do I handle excess characters read from cin?

In the code below when I run it and if I entered more than 30 character while the runtime It will not read linesNum1 nor text[] at all.

So I think it stores the extra character from array1[30] and uses it in linesNum1.

So how can I clear the cache of the program, or make it cin the linesNum1 and text[] even if I entered more characters than array1 can hold?

char array1[30];
for (int i = 0; i<30; i++)
    cin >> array1[i];
int linesNum1;
cin >> linesNum1;
int linesNum2 = linesNum1*80;

char text[linesNum2];
for (int i = 0; i < linesNum2; i++)
    cin >> text[i];

for (int i = 0; i < linesNum2; i++)
    cout << text[i];

Upvotes: 4

Views: 854

Answers (2)

zakinster
zakinster

Reputation: 10688

You would need to flush the stdin buffer in order to get rid of the possible extra characters.

You can use istream::ignore to discard all available characters in the stream :

//Will discard everything until it reaches EOF.
cin.ignore(numeric_limits<streamsize>::max());

//Will discard everything until it reaches a new line.
cin.ignore(numeric_limits<streamsize>::max(), '\n');

Example :

/* read 30 chars */
for (int i = 0; i<30; i++) cin >> array1[i];
/* discard all extra chars on the line */
cin.ignore(numeric_limits<streamsize>::max(), '\n');
/* clear the stream state flags */
cin.clear();
cin >> linesNum1;
...

Upvotes: 1

Dylan N
Dylan N

Reputation: 517

I believe you are looking for is std::cin.ignore(INT_MAX);.

This will read in and ignore everything until EOF. Also, You will most likely want to do an std::cin.clear(); before this too to reset the stream.

EDIT: Along with cin.ignore() is the optional second parameter to add in:

std::cin.ignore(INT_MAX,'\n');

Which will ignore till the end of line.

Upvotes: 2

Related Questions