-5

我希望用户输入整数 1、2 或 3。如何防止输入小数并导致程序崩溃?

4

2 回答 2

3

In general, you want to practice defensive programming. Assume the user will enter wrong or malicious input and sanitize it properly. In this case, that means assume the user could enter anything, try to parse an int out of it, if possible, and if not, give the user an error message saying that they entered the input incorrectly.

In code, this means reading a line of input, perhaps with fgets() if you are using bog-standard C for a console/terminal application, and using a function like atoi() or strtol(). These will parse the input string and return an integer value. If there is invalid data in the input, they won't flag it. You'll have to do that yourself. This can easily be done by looping through the string, looking for any characters that are not digits. If you find any, print an error message to the user.

If you want any additional details, I can provide them. I will not provide a pile of ready-to-use code, however.

于 2013-10-21T00:39:47.817 回答
1

除了简单的 1-2-3 之外,OP 没有提供太多细节。以下是一个简单的解决方案

// Return 1, 2 or 3 on good input
// else return 0
int Get123() {
  int c = fgetc(stdin);
  if ((c < '1') || (c > '3')) {
    return 0;
  }
  return c - '0';
}
于 2013-10-21T00:49:49.313 回答