Start:

Upsya:

unsigned f; cin >> f; do { if (f == 9) { srand(time(NULL)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { arr[i][j] = -100 + rand() % 200; } } } if (f == 0) { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << "Fill arr[" << i << "][" << j << "]: "; cin >> arr[i][j]; } } } if ((f != 9) && (f != 0)) { cout << "Error! Try again: "; cin >> f; } } while ((f != 9) && (f != 0)); 

Reported as a duplicate by D-side , Abyx , Vladimir Martyanov , Harry c ++ Nov 8 '17 at 2:55 pm

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • And you can still ask: how to protect the program not only from asterisks, exclamation marks, etc., as well as from Russian and English letters? - John
  • Describe what you think is not accurate work. Also describe how you think your code should work - Victor

1 answer 1

instead of cin >> f , use getline .

And accordingly, read the line.

 string f; getline(cin, f); do { if (f == "9") { srand(time(NULL)); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { arr[i][j] = -100 + rand() % 200; } } } if (f == "0") { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { cout << "Fill arr[" << i << "][" << j << "]: "; cin >> arr[i][j]; } } } if ((f != "9") && (f != "0")) { cout << "Error! Try again: "; getline(cin, f); } } while ((f != "9") && (f != "0")); 

geline reads the entire line before the newline (enter). The newline itself also reads, but does not save to the string. This behavior corresponds to what you expect.

  • Okay, thanks a lot, you can push everything in the switch - case for the same analogue, because if I press *, d, f the program crashes again. Writes that swtich needs an integer or enum type. - John
  • Does the program crash the one I mentioned, or did you switch / case and the compiler refuses to compile? - KoVadim
  • No, your program works perfectly, in the future I will always use this type of data when working with the user menu, thank you very much! There is another case: I want to make sure that it does not break not only in filling the array, but also in the main function of the program: in the user menu I used switch - case and threw functions there, but all the case clauses contain a number: 1.2 3,4,5, but if I press *, f, then the program will break. I tried to add the string type there again, but switch () swears. - John
  • there can only be an enum type in switch. The string is not such, and one character - yes. Therefore, you can simply start to check the string for the length and take the first character. - KoVadim
  • Everything, changed type to char. Thank you very much! - John