开发者

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++)
{
 开发者_StackOverflow   charray[i] = getchar();
    printf ("%c\n",charray[i]);
    scanf ("%d", &inarray[i]);
    printf ("%d\n",inarray[i]);
}


You can do like this.

while((c = getchar()) != '\n')
{
    putchar(c);
}

this may solve your problem. or you can go till EOF also.


You are reading from the standard input with 2 functions: getchar() and scanf(). You need to understand how they work.

getchar() is easy: it returns the next available character in the input stream (or waits for one or returns EOF)

scanf("%d", ...) is more complex: first, it optionally discards whitespace (spaces, enters, tabs, ...), then it reads as many characters as possible to represent an integer, and stops at the first character that can't be used for integers, like a '\n'.

As you have them in a loop, your getchar() call will get the character that stopped the scanf() and the next scanf() will procedd from there.

If your input is something like "q1w22e333r4444" (with MAX == 4), your program will work.

If your input is something like

q 1
w 22
e 333
r 4444

after the first time through the loop (where charray[0] gets 'q' and inarray[0] gets 1), the getchar() will get '\n' leaving the 'w' "ready" for scanf, which of course fails ... and is then "caught" by the next getchar(); and the "22" gets assigned in the 3rd time through the loop (to inarray[2]).

So, you need to review your code.

Also, scanf() returns a value. Use that value

if (scanf("%d", &inarray[i]) != 1) /* error */;


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]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜