为什么第一个printf不起作用,而另外两个使用相同的结构?

时间:2018-03-10 11:34:47

标签: c

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

int main (void)
{ 
    struct Numbers
    {
        char cell[21];
        char home[21];
        char business[21];
    };

    // Declare variables here:

    struct Numbers numbers;
    char prompt;

    printf("Do you want to enter a cell phone number? (y or n): ");
    scanf("%s", &prompt);
    if (prompt == 'y' || prompt == 'Y')
    {
        printf("Please enter the contact's cell phone number: ");
        scanf("%s", numbers.cell);
    }

    printf("Do you want to enter a home phone number? (y or n): ");
    scanf("%s", &prompt);
    if (prompt == 'y' || prompt == 'Y')
    {
        printf("Please enter the contact's home phone number: ");
        scanf("%s", numbers.home);
    }

    printf("Do you want to enter a business phone number? (y or n): ");
    scanf("%s", &prompt);
    if (prompt == 'y' || prompt == 'Y')
    {
        printf("Please enter the contact's business phone number: ");
        scanf("%s", numbers.business);
    }

    printf("\n");

    printf("Phone Numbers:");
    printf("\n");
    printf("Cell phone number: %s", numbers.cell);
    printf("\n");
    printf("Home phone number: %s", numbers.home);
    printf("\n");
    printf("Business phone number: %s", numbers.business);
    printf("\n");

    printf("Structure test for Name, Address, and Numbers Done!");

    return 0;
}

以下是输出的外观: enter image description here

家庭电话和商务电话工作时,手机号码为空。 一旦我输入错误作为y-> 12345-> y-> 12345-> y12345-> 12345,则所有3个数字都正确显示。我无法找到问题所在。

错误输入的结果: enter image description here

1 个答案:

答案 0 :(得分:1)

打印输出的问题来自覆盖结构的第一个成员。

字节序列su - pi正被写入单字节User=pi ,这几乎可以肯定是{'y', '\0'}的第一个字节。因此,将prompt字段的第一个字符设置为numbers,使其成为空字符串。

如果要在cell中使用字符串格式'\0',则"%s"必须为字符串类型。 Char变量无法保存由scanf("%s", &prompt);读取的字符加上空字符串终止符。

更自然和典型的方法是使用prompt进行字符读取。提出了两种方式。

注1: scanf转换说明符不会自动跳过任何前导空格,因此如果输入流中存在杂散换行符(例如,来自前一个条目),则scanf调用将立即使用它。 / p>

解决此问题的一种方法是在转换说明符之前的格式字符串中放置一个空格:

" %c"

注2:通常我们在%c之前声明结构,以在文件中为它们提供全局范围。

注3:另外,如果将scanf(" %c", &c); 声明为本地结构变量,则所有结构成员都是未定义的。如果用户跳过填写该号码,您可能会获得该字段的垃圾打印输出。您有义务自己初始化这些成员。

main

输出:

numbers