简体   繁体   中英

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

Compiler : Gcc Linux 32-bit

#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? If I input integers it works fine.

scanf() is reading the newlines. 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.

This is because newline character ( \\n on Unix/Linux) is left behind by scanf() for the next call of scanf() (in this case). Change 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.

\\n is consumed by scanf() that's why the rest 2 characters are not taken.

Add a leading space before %c

Change to:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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