Search code examples
carrayscharskip

Scanning a single char into an array C Programming


I am having a problem scanning chars into an array. Every time I do it will skip the next scan and go to the next. I know what is happening because the input also adds '\n' to the input but I do not know how to remedy the cause of it. Here is some sample code:

char charray [MAX], ffs;
int inarray [MAX], i;


for (i = 0; i < MAX; i++)
{
    charray[i] = getchar();
    printf ("%c\n",charray[i]);
    scanf ("%d", &inarray[i]);
    printf ("%d\n",inarray[i]);
}

Solution

  • You should actually scan a string into the array directly, rather than characters using scanf("%s",&charray);

    However your code will work if you add a while(getchar() != '\n' ); statement. This will get all characters till the '\n'.

    charray[i] = getchar();
    do{
        c = getchar();
    }while(c != '\n' && c!= EOF);
    printf ("%c\n",charray[i]);
    scanf ("%d", &inarray[i]);
    do{
        c = getchar();
    }while(c != '\n' && c!= EOF);    
    printf ("%d\n",inarray[i]);