UVa 在线判断 ANSI C Runtime Error with scanf but Accepted with gets combined with sscanf

UVa Online Judge ANSI C Runtime Error with scanf but Accepted with gets combined with sscanf

我将省略整个代码,但到目前为止这些测试可能非常令人不安:

这已被 ANSI C、C++ 和 C++ 11 接受

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int p, q, r, s, t, u;
    char* str = malloc(1000);
    while(gets(str) != NULL) {
        sscanf(str, "%d %d %d %d %d %d", &p, &q, &r, &s, &t, &u);
        printf("%d %d %d %d %d %d\n", p, q, r, s, t, u);
    }
}

令人不安的事实来了,此代码在 ANSI C 中出现运行时错误,但在 C++ 和 C++ 11 中被接受:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int p, q, r, s, t, u;
    //== 6 instead of != EOF also gives me a runtime error
    while(scanf("%d %d %d %d %d %d", &p, &q, &r, &s, &t, &u) != EOF) {
        printf("%d %d %d %d %d %d\n", p, q, r, s, t, u);
    }
}

您忘记了 return 0; - 在 C 中,这意味着 main() return 是 shell 的垃圾状态。在 C++ 中,允许省略 return 0;,默认状态 0 (== EXIT_SUCCESS) 将被 returned。然而,在 C 中,您的两个程序都将 return 处于未定义状态。在第一种情况下,你碰巧很幸运,0 被 returned。在第二种情况下,不是 0 的东西被 returned(可能是 -1)。尝试养成始终从 main return 获取有效状态的习惯,无论您使用的是 C 还是 C++。

有关详细信息,请参阅 this excellent question and answer

另请注意,在启用警告的情况下进行编译(例如 gcc -Wall ...)会立即提醒您注意此错误并节省您一些时间。