scanf() 函数的魔力?

发布于 2024-09-04 01:37:00 字数 233 浏览 2 评论 0原文

为什么运行这段代码并打印整个字符串?

#include <stdio.h>

void main()
{
    int a;
    while(a!='q')
    {
        scanf("%c",&a);
        printf("%c",a);
    }
}

输入除q之外的字符串,最后按回车键。现在您的字符串才会打印在屏幕上。为什么?

Why run this code and print whole string?

#include <stdio.h>

void main()
{
    int a;
    while(a!='q')
    {
        scanf("%c",&a);
        printf("%c",a);
    }
}

Enter string except q, and finally press enter key. Only now your string will print on the screen. Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

酒中人 2024-09-11 01:37:00

这里的问题不在于 scanf,而在于您的 printf 调用。

Printf 会缓冲输出,直到到达新行,因此程序在 printf("\n"); 之前不会显示任何内容。 (当有人按 Enter 时也会发生这种情况,您将他们的返回值输出到屏幕,这会导致缓冲区刷新。)

如果您不想使用 printf("\n") 分解您的输出,然后您可以使用 fflush(stdout) 手动刷新缓冲区而不打印任何内容,如下所示:

int a;
while(a!='q')
{
    scanf("%c",&a);
    printf("%c",a);
    fflush(stdout);
}

The problem here is not with scanf, it is with your printf call.

Printf buffers output until a new line is reached, so the program will not display anything until you printf("\n");. (Which also happens when someone presses enter, you output their return to the screen which causes the buffer to flush.)

If you don't want to break up your output with printf("\n"), then you can use fflush(stdout) to manually flush the buffer without printing anything, like this:

int a;
while(a!='q')
{
    scanf("%c",&a);
    printf("%c",a);
    fflush(stdout);
}
老子叫无熙 2024-09-11 01:37:00

对于初学者来说,该代码无法编译 - print 不是 C 中的函数, printf 是您正在寻找的函数。

至于我认为你要问的问题,我不知道你为什么要打印你读到的每个字符,直到你读到 q;这似乎有点毫无意义。

Well for starters, that code won't compile - print is not a function in C, printf is one one you're looking for.

As for what I think you are asking, I don't know why you would want to print every character you read until you read q; it seems kinda pointless.

孤独患者 2024-09-11 01:37:00

首先,您需要将 a 定义为 char 类型:

char a;

当您按 Enter 时,while 循环将运行您输入的字符数。尝试以下操作看看发生了什么:

char a = 0;
int i = 0;
while(a!='q')
{
    scanf("%c",&a);
    printf("%d:%c",i++,a);
}

At first you need to define a to be of char type:

char a;

When you hit enter, the while loop will run for so many times as many characters you have inputed.Try this to see what is happening:

char a = 0;
int i = 0;
while(a!='q')
{
    scanf("%c",&a);
    printf("%d:%c",i++,a);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文