c - 正在跳过一个特定的变量引用

标签 c

看起来像%s决赛printf完全被跳过。

这是完整的代码:

#include <stdio.h>

int main(void){
    char address[100];
    char city[100];
    char state[2];
    char zip[15];

    printf("Enter street address: ");
    scanf(" %[^\n]",&address);

    printf("Enter city: ");
    scanf(" %[^\n]",&city);

    printf("Enter state: ");
    scanf(" %s",&state);

    printf("Enter ZIP Code: ");
    scanf(" %s",&zip);

    printf("%s\n%s, %s %s",address,city,state,zip);

    return 0;
}

输入此地址后:

1 Main Street
New York City, NY 12345

程序打印:

1 Main Street
, NY 12345

我无法找出此问题的原因。 任何帮助将不胜感激,因为我没有主意。

最佳答案

#include <stdio.h>

int main(void){
    char address[100];
    char city[100];
    char state[2];
    char zip[15];

    printf("Enter street address: ");
    scanf(" %[^\n]",&address);

    printf("Enter city: ");
    scanf(" %[^\n]",&city);

    printf("Enter state: ");
    scanf(" %s",&state);

    printf("Enter ZIP Code: ");
    scanf(" %s",&zip);

    printf("\nONE: %s\n",address);
    printf("TWO: %s\n",city);
    printf("THREE: %s\n",state);
    printf("FOUR: %s\n",zip);

    return 0;
}

将其复制粘贴到 https://www.codechef.com/ide 中,您将看到以下输出:

Enter street address: Enter city: Enter state: Enter ZIP Code: 
ONE: 1 Main Street
TWO: New York City, NY 12345
THREE: 
FOUR: @

您将所有内容存储在 city 中,而不是停在逗号处。您认为您的 scanf for city 正在做什么?

关于c - 正在跳过一个特定的变量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54643158/

相关文章:

c++ - emacs C/C++ 缩进 : different for pre and post comments//or: how can I make certain comments like//^ be indented extra?

c - 如何在数组开头追加字符串?

c - 使用打开/读取时如何检测文件结尾?

c 数据类型大小

C 编译器 : not found in Clion

c - 浮点加法/乘法/除法

c - 坚持使用 USART stm32f103rct6

c - 使用 C 中的简单字节协议(protocol)读/写大整数或 float

C++/C语言独立内存分配

c - 内核编译但不会与 unistd.h 引用链接