cgccstdinfflush

How to read characters from stdin into an array in c?


I last did C in 1991 and now I'm helping a friend with homework.

He has to get characters from stdin into an array. Seems simple enough. I figured I'd use this question as a reference point.

We have this:

    printf("Input the line\n");
    i=read(0, arg, sizeof(char)*9);

IIUC that gets us the characters and based on the answer comment we should be able to put the characters directly into the arg array like this:

   while ((c = getchar()) != '\n' && c != EOF  && i2<9 ) {
     arg[i2] = c;
     i2++;
   }

However that prints this (repl.it link):

 ./main
Input the line
123 456 789

893 456

So it looks like even though I'm trying to limit it to indices [0,8] by adding i2<9 in the while loop, it still grabs 89 and puts it at the beginning of the array since the array only fits 9 characters.

Why is this? And am I going about this the right way?

We are not allowed to use fpurge. I assume the professor is trying to teach them how to do this manually...


Solution

  • I don't understand what you are trying to do here,

       while ((c = getchar()) != '\n' && c != EOF  && i2<9 ) {
         arg[i2] = c;
         i2++;
       }
    

    The above loop is mainly used to consume the left over input in the input stream after read.


    That is, with

    i=read(0, arg, sizeof(char)*9);
    

    You are reading 9 chars into arg but you entered 11 chars along with \n.

    Thus arg will have contents,

      123 456 (null)   <---contents
      01234567 8       <---indexes
    

    remember still 89\n is left in the stream. thus with while loop you are reading 89 into arg array from index 0.