我正在使用多个scanfs在C语言中编写程序,但是在运行它时,每当我进入正在读取整数值的扫描时,它会跳过它并放入一个开始执行无限循环的不同值。我甚至尝试将每个scanfs分成多个函数,同样的事情发生了。我绝对不知道出了什么问题,或者为此做了什么。
答案 0 :(得分:2)
检查返回值。 C库函数返回状态代码是有原因的。
答案 1 :(得分:2)
人们使用scanf
打击的主要问题是数据不是他们所期望的。这可能导致部分扫描,使您处于文件中的意外点以供将来扫描。这个可能会导致你的无限循环,你通常会通过确保返回值是你所期望的(你试图扫描的项目数)来检测它。没有看到代码就很难说。
C99在7.19.6.4 The scanf function
部分说明:
如果在任何转换之前发生输入故障,scanf函数将返回宏EOF的值。否则,scanf函数返回分配的输入项的数量,如果早期匹配失败,则可以少于提供的数量,甚至为零。
但是,几乎总是应该将输入检索为行,然后使用sscanf
从那里进行处理,因为这样可以轻松地对不同格式的输入数据进行多次扫描字符串,用于确定该行所用格式的次数。
例如,以下代码是一种通过缓冲区溢出保护和检测来检索用户输入的安全方法,以及缓冲区清除,因此多余的输入不会影响下一个输入操作:
#include <stdio.h>
#include <string.h>
#define OK 0
#define NO_INPUT 1
#define TOO_LONG 2
static int getLine (char *prmpt, char *buff, size_t sz) {
int ch, extra;
// Get line with buffer overrun protection.
if (prmpt != NULL) {
printf ("%s", prmpt);
fflush (stdout);
}
if (fgets (buff, sz, stdin) == NULL)
return NO_INPUT;
// If it was too long, there'll be no newline. In that case, we flush
// to end of line so that excess doesn't affect the next call.
if (buff[strlen(buff)-1] != '\n') {
extra = 0;
while (((ch = getchar()) != '\n') && (ch != EOF))
extra = 1;
return (extra == 1) ? TOO_LONG : OK;
}
// Otherwise remove newline and give string back to caller.
buff[strlen(buff)-1] = '\0';
return OK;
}
您可以使用以下内容调用此代码:
char buff[50];
int rc = getLine ("What?> ", buff, sizeof(buff));
if (rc != OK) {
// Error condition, either EOF or to long.
}
// Now use sscanf on buff to your heart's content,
// remembering to check the return value.
答案 2 :(得分:0)
如果您正在从stdin读取,则scanf将从缓冲区中读取,该缓冲区在您按下返回时结束。
第一个scanf将接收您正在寻找的内容,但剩余的缓冲区将保留。
代码:
int num;
scanf("%d", &num);
并输入:
1 2 3 4 5
按预期,num将为5。但是
2 3 4 5
仍将在缓冲区中,因此您运行的下一个scanf将不会提示输入另一个输入,而是将其作为输入。
您的scanf可能正在读取先前缓冲区中的残留数据。