Search code examples
cloopscharscanfwhitespace

Problem with reading characters into an array one by one (C)


I'm trying to read a collection of characters, typed one after another (with spaces) and save them all in an array. For example, the input "a b c d e f" would be kept as "abcdef" in a string (a character of arrays). However, problems arise when I try to read content for two arrays one after another, like here:

void receive_pool_content (char pool[], int pool_size)
{
    for (int i=0; i<pool_size; i++)
    {
        scanf("%c", &pool[i]);
        if (pool[i]==' ') --i;
    }
}

int main()
{
    char pool1[6];
    char pool2[6];
    receive_pool_content(pool1,6);
    receive_pool_content(pool2,6);
  printf("%c", pool2[5]);
    return 0;
}

The first array, pool1, comes out fine ("abcdef"), but the second one is lacking the first letter (for the input "q w e r t y", it comes out as "\nqwert").

I really am completely clueless as to why it behaves like that. Any tips would be very helpful :).


Solution

  • The format specification "%c" allows to read all characters including white space characters (in particularly the new line character '\n')

    Instead write:

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

    Pay attention to the leading space in the format specification. It allows to skip white space characters.

    That is the function will look like

    void receive_pool_content (char pool[], int pool_size)
    {
        for (int i=0; i<pool_size; i++)
        {
            scanf(" %c", &pool[i]);
        }
    }