【发布时间】:2013-01-28 18:04:57
【问题描述】:
是否可以在 C 中处理数据类型不匹配异常?
在 C++ 和其他高级语言中,代码通常被 try...catch 包围。但是,由于C语言中没有异常处理机制,我们如何处理数据类型不匹配异常呢?
例如,假设我有一个程序要求用户输入一个整数。如果用户误打了字母字符,程序就会崩溃。我如何在 C 中处理这个问题?
这里是一些示例代码:
#include "stdafx.h"
void main()
{
int x = 0;
printf("Hello World!\n\n");
printf("Please enter an integer: ");
scanf("%d", &x);
printf("\n");
printf("The integer entered is %d", x);
printf("\n\n");
printf("Press any key to exit!");
getchar();
getchar();
}
【问题讨论】:
-
错误检查?如果您的程序因无效输入而崩溃,则说明您验证的不够充分。
-
有人可以举个例子吗?我对 C 编程语言很陌生。
-
这根本不是 C 特定的。大概有检查网络上可用函数的返回值的四分之一的例子。
-
@BartFriederichs 我贴了一些代码
-
@Matthew - 你需要检查
scanf("%d", &x);的返回值。阅读手册页。
标签: c exception types mismatch