Why doesn't the first letter get into the array if this program is used?

Viewed 373
#include <stdio.h>

int main(int argc, char **argv){
    int c;
    char str[10];
    while ((c=getchar()) != '\n') {
        scanf("%s",str);
    }

    printf("%s\n", str);
}

If the input is "Data", the output is "ata" where the "D" is missing. Can't figure out why. Any explanation?

4 Answers

In your program,

while ((c=getchar()) != '\n') {
        scanf("%s",str);
}

the getchar will absorb the first character, then the scanf will take all but the last '\n', which will end the while loop.

Thus str misses the first char.

Change to

do  {
        scanf("%s",str);
} while ((c=getchar()) != '\n');

to get the whole string. Or simply remove the loop and getchar()...

When you use getchar() to get the character, it takes the first character "D" of input "Data".

The actual value of str variable is "ata".

Use putchar() and try this code snippet to verify the values of your variable c and str.

#include <stdio.h>

int main(int argc, char **argv){
    int c;
    char str[10];
    while ((c=getchar()) != '\n') {
        //to display the value of c
        putchar(c);
        scanf("%s",str);
    }

    printf("%s\n", str);
}

Your getchar is consuming the first letter of your string, while the scanf is consuming the rest in a single iteration.

The difference between scanf and getchar is that scanf is a formatted method of reading input from the keyboard while getchar reads a single character from the keyboard at a time.

So either use the getchar in the while loop, or use scanf (with no loops) if you know what the input format is supposed to be, which you can configure with the format specifiers.

getchar: http://www.cplusplus.com/reference/cstdio/getchar/

scanf: http://www.cplusplus.com/reference/cstdio/scanf/

The difference: C getchar vs scanf

getchar() function used to only fetch one character not whole String

If you want to fetch whole string than simple remove loop

scanf("%s",&str)// str is simple variable or array

And onther solution is

while(c=getchar()!='\n')
{
  str[i]=c;
}
str[i]='\0';
Related