需要有关输入字符串并将其打印出来的帮助

时间:2017-10-26 22:25:45

标签: c

我被困在正在撰写的作业的一部分上。

当我输入postalCode(A8A 4J4)时,它会显示

output1

output2

应该是:

Postal code: A8A 4J4
City: Toronto

正在跳过进入城市的选项。

我已经尝试了%[^\n],但它仍然跳过进入城市的选项。

我目前的代码是:

if (option == 'y' || option == 'Y') {
    printf("Please enter the contact's apartment number: ");
    scanf("%u", &address.apartmentNumber);

    printf("Please enter the contact's postal code: ");
    scanf("%s", &address.postalCode);
}

if (option == 'n' || option == 'N') {
    printf("Please enter the contact's postal code: ");
    scanf("%s", &address.postalCode);
}

printf("Please enter the contact's city: ");
scanf("%40s", address.city);

printf("Postal code: %s\n", address.postalCode);
printf("City: %s\n", address.city);

我已经看过一篇关于此的帖子,但那里的答案并没有帮助。我已经在scanf中尝试了[^ \ n]。

2 个答案:

答案 0 :(得分:1)

字符串输入越好fgetsscanf ("%[^\n]%*c", &address.city);如果该行仅"\n"或太长,则无法正常工作。坚持fgets()

 fgets(address.city,40,stdin);

编辑:如果您仍想使用scanf像这样使用

 scanf (" %[^\n]%*c", &address.city)

它将扫描字符,直到找到'\n'

答案 1 :(得分:0)

&放在address.city的引用上 像这样

scanf("%40s", &address.city);
相关问题