ccharacter-arrays

Character Arrays using


I want to use scanf_s("%c\n", &arr[index]) to input once character at a time in a single line using for/while loop. I cannot figure out how to output the result. Below is the code.(I only want to use scanf statement. fgets way is easy.

printf("\nEnter the lowercase letters\n");
for (index = 0; index < size; index++)
{
    scanf_s("%c\n", &arr[index]);
    _getch();
}
printf("\nThanks"); 
for (index = 0; index < size; ++index)
{
    printf("%c/n", arr[index]);
}

It takes the input but exits out after thanks statement. I cannot figure out why. Although I have used a different method that works. It's just a variation I was trying.


Solution

  • Change

    scanf_s("%c\n", &arr[index]);
    _getch();
    

    To

    scanf_s(" %c", &arr[index], 1);
    

    When scanning a character(%c) or string(%s) using scanf_s, you must supply an additional value as a parameter which indicates the amount of characters to be scanned.
    The space before %c discards all whitespace characters(newlines, spaces etc) including none before scanning a non-whitespace character.

    Also, the printf in the loop has /n instead of \n for a newline.