为什么 C 程序使用 Scanf 给出奇怪的输出?

Why is the C program giving weird output using Scanf?

我目前正在学习 C 编程并且遇到了这个奇怪的输出。

// Program will try functionalities of the scanf function
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char const *argv[])
{
    char array[40];
    scanf("Enter your address: %39s",array);   //39 + 1/o null character at the end of the character array.
    printf("The address is : %s", array);
    return 0;
}

它应该接受输入地址并输出相同的地址。

PS C:\Users\G\Documents\C programs> gcc scanff.c -o scanff -Wall -pedantic -std=c99
PS C:\Users\G\Documents\C programs> ./scanff
jhgjhg
The address is : ■   a

那个黑块是什么?有人可以解释一下吗! 谢谢

两个问题:

  • 您没有正确初始化 array。应该是:

    char array[40] = "";

  • 您在以下语句中混淆了 scanf 和 printf:

    scanf("Enter your address: %39s",array);

    应该分解为:

    printf( "Enter your address: " );

    scanf ("%39s", array);

只需为 scanf() 函数正确使用格式说明符并使用 printf() 显示自定义消息。

看看下面的代码:

// Program will try functionalities of the scanf function
#include<stdio.h>
#include<stdlib.h>

int main(int argc, char const *argv[])
{
    char array[40];
    printf("Enter your address: ");
    scanf("%39s",array);   //39 + 1/o null character at the end of the character array.
    printf("The address is : %s", array);
    return 0;
}

你应该再看看scanf的文档。 格式字符串应包含格式规范和要按字面匹配的非格式字符。 您似乎假设可以使用 scanf() 进行提示,这是不正确的。

使用此(未经测试的)代码您可能会取得更大的成功:

int main(int argc, char const *argv[])
{
    char array[40];
    printf("Enter your address: ");
    scanf("%39s",array);   //39 + 1/o null character at the end of the character array.
    printf("The address is : %s\n", array);
    return 0;
}

检查 scanf() 调用的结果以查看是否读取了预期数量的值也是一种很好的做法。在您的情况下,该值可能是 0,因为文字字符在您的输入中不匹配。当不使用格式规范时,目标变量的值不变(在这种情况下未定义,因为数组包含恰好在分配变量的堆栈上的字节。)

来自 scanf 的手册页:

int scanf(const char *format, ...);

未定义输出的原因:

Each conversion specification in format begins with either the character '%' or the character sequence "%n$"

解决方案:将scanf("Enter your address: %39s",array);改为scanf("%39s",array);