How to handle extra characters read from cin?

In the code below, when I run it, and if I entered more than 30 characters at runtime, it will not read linesNum1 and text[] .

Therefore, I think that it stores an extra character from array1[30] and uses it in linesNum1 .

So, how can I clear the program cache or make it cin 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]; 
+4
source share
2 answers

You will need to flush the stdin buffer to get rid of 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; ... 
+1
source

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

This will read and ignore everything before the EOF. In addition, you will most likely want to do std::cin.clear(); before that also to reset the stream.

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

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

Which will ignore until the end of the line.

+2
source

Source: https://habr.com/ru/post/1485824/


All Articles