当用户输入不正确的值以避免程序崩溃时,C 中的数据验证 [英] Data Validation in C when the user inputs an incorrect value to avoid program crash

查看:50
本文介绍了当用户输入不正确的值以避免程序崩溃时,C 中的数据验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何确保用户只输入一个整数值,以免程序崩溃?

How do I ensure that the user inputs only an integer value so that the program wont crash?

如果用户输入的不是整数,我想:printf("请重新检查您的输入);

If the user inputs anything else than an integer, I want to: printf("Please re-check your entry);

printf("How many values do you want to enter? \t");
    int g;
    scanf("%d", &g);

推荐答案

我想说,检查 scanf 的返回值:

I would say, check the return value of scanf:

这些函数返回成功匹配和分配的输入项的数量,该数量可能少于提供的数量,甚至在早期匹配失败的情况下为零.

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

如果在第一次成功转换或匹配失败之前到达输入的末尾,则返回值 EOF.如果发生读取错误,也会返回 EOF,在这种情况下,流的错误指示符(请参阅 ferror(3))被设置,并且 errno 被设置指示错误.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream (see ferror(3)) is set, and errno is set indicate the error.

这篇关于当用户输入不正确的值以避免程序崩溃时,C 中的数据验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆