我在解析 Auction Problem 中的输入文件时遇到问题的Facebook HackerCup .
输入文件的每一行包含 9 个空格分隔的整数:N、P1、W1、M、K、A、B、C 和 D。根据输入约束,数字可以大到 10^18。因此,我决定使用long long int
来存储变量。
我正在做:
FILE *fr;
long long int N, P1, W1, M, K, A, B, C, D;
char line[1024];
fr = fopen ("input.txt", "rt");
while(fgets(line, 1024, fr) != NULL)
{
sscanf(line, "%lld %lld %lld %lld %lld %lld %lld %lld %lld", &N, &P1, &W1, &M, &K, &A, &B, &C, &D);
printf("N:%lld P1:%lld W1:%lld M:%lld K:%lld A:%lld B:%lld C:%lld D:%lld\n\n", N, P1, W1, M, K, A, B, C, D);
}
对于一行81834165 9999991 1 9999991 9999989 389999650 169999844 799999121 149999837
,我得到N:81834165 P1:4367 W1:9999991 M:4 078336 K:1 A:2292512 B:9999991 C :2292488 D:9999989
您能帮我指出这段代码中的问题吗?任何有关解析类似文件的建议也将不胜感激。
<小时/>编辑:我应该补充一点,它适用于 int
变量,如下所示:
char line[1024];
int N, P1, W1, M, K, A, B, C, D;
strcpy(line, "81834165 9999991 1 9999991 9999989 389999650 169999844 799999121 149999837");
printf("Line: %s", line);
sscanf(line, "%d %d %d %d %d %d %d %d %d", &N, &P1, &W1, &M, &K, &A, &B, &C, &D);
printf("ret_val:%d\n\n", ret_val);
printf("N:%d P1:%d W1:%d M:%d K:%d A:%d B:%d C:%d D:%d\n\n", N, P1, W1, M, K, A, B, C, D);
<小时/>
我刚刚注意到一些奇怪的事情。在一个 printf()
中打印多个 long long int
变量会输出错误的值,而在单独的 printf()
中打印它们会输出正确的值。我的意思是:
printf("N:%lld P1:%lld\n", N, P1);
printf("N:%lld\n", N);
printf("P1:%lld\n", P1);
输出:
N:81834165 P1:2009288239
N:81834165
P1:9999991
你对此有什么想法吗?
<小时/>解决方案
我发现问题出在我使用的编译器上(MinGW 上的 gcc)
在此编译器上,我需要将 %lld
替换为 %I64d
。我在this post发现了类似的问题.
最佳答案
显然,%lld
无法正常工作。根据this page ,“您应该使用 %I64d
而不是 %lld
,因为 MinGW 使用 MSVCRT。”
希望这有帮助!
关于c - sscanf 对于 long long int 变量返回错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8987698/