Question

I made a program in C that reads an array of characters. It didn't work properly.

#include <stdio.h>

int main()
{
    char a[50];
    int n, i;
    scanf("%d", &n);
    for(i=0; i<n; i++)
        scanf("%c", a+i);
    for(i=0; i<n; i++)
        printf("%c ", *(a+i));
    return 0;
}

This program didn't read the characters I wanted.

For input

5
a b c d e

program printed

 a   b   

When I changed scanf("%c", a+i) to scanf(" %c", a+i) it worked fine.

Can somebody explain me why didn't the first code work as I wanted?

Was it helpful?

Solution

scanf("%c", a+i); did not work because it consumes the newline left in the stdin buffer in the previous scanf call. The %c conversion specifier in the format string of scanf matches a character and the usual skip of leading white space is suppressed. When you add a leading space in the format string of scanf

scanf(" %c", a + i);
   //  ^ note the leading space

means scanf will read and discard any number of leading whitespace characters. Thus it works in your case.

OTHER TIPS

The blank space its also a character. You can refer to the the documentation here :

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

You were reading new line after 5, 2 chars, 2 spaces.

Read carefully the documentation of scanf(3) (which is a standard C function, not idiomatic C++).

In its format string:

   ·      A sequence of white-space characters (space, tab, newline,
          etc.; see isspace(3)).  This directive matches any amount of
          white space, including none, in the input.

A more C++ specific way would be to use operator >> or the get member function of std::istream

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top