C中输入错误数据类型如何处理
C程序中,运用scanf()输入数据时,不小心输入非法字符,即程序中是float类型变量,用户输入字符a,程序运行出错,用什么方法可以避免这样的错误发生?
你可以在需要输入整数的时候,你输入字符试试,会提示你输入错误,并显示相应的错误代码!
程序代码:
#include <stdio.h> #if defined(_MSC_VER) #define FLUSH(strm) ((strm)->_cnt = 0) #else #define FLUSH(strm) FlushInputStream(strm) #endif void FlushInputStream(FILE *strm) { int ch; do ch = getc(strm); while (ch != '\n' && ch != EOF); } void PrintError(char const* msg, FILE *istrm) { fputs(msg, stderr); FLUSH(istrm); } int GetInt1(int* value) { return scanf("%d", value) == 1 && 0 < *value && *value < 6; } int GetInt2(int* error ) { int value = 0; if (!(scanf("%d", &value) == 1 && 0 < value && value < 6)) { *error = 1; } return value; } static int errorCode; int GetInt3() { int value = 0; errorCode = !(scanf("%d", &value) == 1 && 0 < value && value < 6); return value; } int main() { int value; int error ; if (GetInt1(&value)) printf("read %d\n", value); else PrintError("GetInt1 failed\n", stdin); error = 0; value = GetInt2(&error); if (error == 0) printf("read %d\n", value); else PrintError("GetInt2 failed\n", stdin); errorCode = 0; value = GetInt3(); if (errorCode == 0) printf("read %d\n", value); else PrintError("GetInt3 failed\n", stdin); system("PAUSE"); return 0; }