简体   繁体   English

scanf只能将3个字符读取到5个位置的char数组中

[英]scanf can only read 3 characters into a 5 position char array

Compiler : Gcc Linux 32-bit 编译器:Gcc Linux 32位

#include<stdio.h>

int main()
{
    int i;
    char a[5];

    for(i=0;i<5;i++)
        scanf("%c",&a[i]);

    for(i=0;i<5;i++)
        printf("%c",a[i]);
} 

Why does this array a accepts only three characters even though I have specified it to take 5 characters? 为什么即使我已将数组指定为5个字符,该数组a只接受三个字符? If I input integers it works fine. 如果我输入整数,则可以正常工作。

scanf() is reading the newlines. scanf()正在读取换行符。 If you entered 'a' , 'b' , and 'c' , and hit Enter after each one, then a would contain {'a', '\\n', 'b', '\\n', 'c'} , and the final '\\n' would not be read. 如果输入了'a''b''c' ,并在每个输入后都按Enter ,则a将包含{'a', '\\n', 'b', '\\n', 'c'} ,最后的'\\n'将不会被读取。

This is because newline character ( \\n on Unix/Linux) is left behind by scanf() for the next call of scanf() (in this case). 这是因为换行符( \\n在Unix / Linux)是由留下scanf()用于下次调用scanf() (在这种情况下)。 Change scanf("%c",&a[i]); 更改scanf("%c",&a[i]); to

scanf(" %c",&a[i]);  
       ↑
   space before specifier  

When putting a space before %c , scanf() skips any number of white-space characters in the input. %c之前放置空格时, scanf()在输入中跳过任意数量的空白字符。

\\n is consumed by scanf() that's why the rest 2 characters are not taken. \\nscanf()占用,这就是为什么其余两个字符不被占用的原因。

Add a leading space before %c %c之前添加一个空格

Change to: 改成:

scanf(" %c", &a[i]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM