c - 当我使用 scanf() 时,我想知道这两者有什么不同

标签 c

我不知道如何用语言来解释这个,所以我先给你一个问题。所以如果你之前有过同样的问题,请原谅我。

#include <stdio.h>

int main()
{
    int a, b;

    scanf("%d %d", &a, &b);
    printf("%d %d", a, b);

    return 0;
}
#include <stdio.h>

int main()
{
    int a, b;

    scanf("%d%d", &a, &b);
    printf("%d %d", a, b);

    return 0;
}

我一直想知道 scanf("%d %d", &a, &b);scanf("%d%d", &a, &b); 的区别 code> 当我编码的时候。所以我的问题是,这两个代码在功能上是否相同?

最佳答案

两段代码之间没有区别。无论哪种方式都有效,您可以使用您喜欢的任何一种。

但是,如果考虑 %c,即 char 数据类型说明符,那么事情就会变得有趣起来。为了理解差异,请考虑以下程序:

    int main()
    {
        char x,y; //declaring two variable of char data type
        printf("Part 1");
        scanf("%c%c",&x,&y); //no space between the specifiers
        printf("%c %c",x,y);
        printf("Part 2");
        scanf("%c %c",&x,&y); //single white space between the specifiers.
        printf("%c %c",x,y);
        return 0;
    }

程序执行时的截图 enter image description here

在第 1 部分中,变量 x 存储字符“A”,变量 y 存储“”(空格)。在这种情况下,空间被视为输入,因此忽略了实际输入。 在第 2 部分中,变量 x 存储“A”,变量 y 存储“B”,因为它明确提到输入中需要空格。

希望这有帮助:)

关于c - 当我使用 scanf() 时,我想知道这两者有什么不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57319732/

相关文章:

c - gdb 命令出错。 eclipse调试问题

c - 如何为指向指针的指针分配内存?

c - 未知的 C 字符串截断/覆盖

通过 "fork"为一个父进程创建多个进程

c++ - MPI 分布式、无序工作

c - 普通C库中有TestAndSet(volatile int *lock)函数吗?

c - 在python中加载c dll

C++ SDL 跳出 while 循环

java - 如何使用两种不同的语言来编写一个程序?

python - 将 C 数组移植到 Python