从C中的stdio扫描字符串和整数

问题描述 投票:0回答:1

我试图以这种格式读取两个整数和stdio的字符串输入:

22 CHEESE 2

分为两个不同的int变量和一个字符串变量,如下所示。

        int newId, newQuantity;
        char newName[20];
        scanf("%d %s %d",&newId, newName, &newQuantity);

代码正确读取字符串,但在输入输入后立即,当我测试以查看newId和newQuantity的值时,它们总是这些大的int不是我输入的。我通过修改我的代码来检查输入的变化,以显示以下内容:

        int newId, newQuantity;
        char newName[20];
        scanf("%d %s %d",&newId, newName, &newQuantity);
        printf("%d %s %d",&newId, newName, &newQuantity);

例如,当我输入22 CHEESE 2时,它会打印-1957382872 CHEESE -1957382868。我想知道是否有任何方法可以纠正这个问题?任何帮助表示赞赏。

c scanf
1个回答
2
投票

这个printf("%d %s %d",&newId, newName, &newQuantity)是错误的,应该是printf("%d %s %d",newId, newName, newQuantity),如果你启用了编译器警告,你会发现它。

这是警告:

$ gcc main.c -Wall -Wextra
main.c: In function ‘main’:
main.c:7:18: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
         printf("%d %s %d",&newId, newName, &newQuantity);
                 ~^        ~~~~~~
                 %ls
main.c:7:24: warning: format ‘%d’ expects argument of type ‘int’, but argument 4 has type ‘int *’ [-Wformat=]
         printf("%d %s %d",&newId, newName, &newQuantity);
                       ~^                   ~~~~~~~~~~~~
                       %ls

这个问题是一个完美的例子,说明为什么在提问时总是应该提供mcve。问题不是你想象的那样,而是在代码中你最初没有告诉我们。它也是一个完美的例子,说明为什么你应该启用编译器警告并阅读它们。他们经常提供非常好的线索。一个警告是编译器说“这段代码有效,但它可能没有你想做的”。

© www.soinside.com 2019 - 2024. All rights reserved.