【问题标题】:Need help about inputting strings and printing it out需要有关输入字符串和打印出来的帮助
【发布时间】:2017-10-26 22:25:44
【问题描述】:

我正在写作业的一部分。

当我输入邮政编码(A8A 4J4)时,它会显示

应该是:

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]。

【问题讨论】:

标签: c


【解决方案1】:

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

 fgets(address.city,40,stdin);

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

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

它会扫描字符直到找到'\n'

【讨论】:

    【解决方案2】:

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

    scanf("%40s", &address.city);
    

    【讨论】:

    • 或者使用这个scanf("%s", &address.city);你需要和号。
    • 我已经尝试了所有方法,发现 scanf(" %[^\n]", &address.postalCode); scanf(" %40s", address.city); 有效。感谢您的帮助。
    猜你喜欢
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多