-5

ユーザーに int 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 に答える