0

I have a C programming assignment that wants me to take multiple numbers space-seperated inputs and store them in array, at the beginning.

Input sample is like:

X 18 34 5

Y 34 56 7

r 10 23 2

The number of lines can be more than that and also spaces between those numbers which are on one line can be more than one.(For example: 23_34 or 23______34)

After taking input i need to hold 3. arr1 = consist of first values of each input), arr2 = consists of second values of each input and arr3 = from first to third values of each input. If i can take the input and assign them temporary variables, i can overcome to put them in the arrays.

I have checked many discussions but none of post could solve my problem.

Probably while(c = getchar() != EOF) can be a solution for this but i couldn't get the logic behind it and also write it properly..

Edit: This is my code


    char a;
    int b,c,d;
    while ((a = getchar()) != EOF){
        ungetc(a,stdin);
        scanf("%c %d %d %d",&a,&b,&c,&d);
        printf("%c %d %d %d\n",a,b,c,d);


Why this code prints also previous values? (click to see the image)

  • Does this answer your question? [Reading string from input with space character?](https://stackoverflow.com/questions/6282198/reading-string-from-input-with-space-character) – OldProgrammer Mar 23 '20 at 17:12
  • 2
    The standard answer is `fgets` and `sscanf`. `fgets` reads an entire line, or returns NULL when the end-of-file is reached. `sscanf` can parse the line and extract the four fields. It ignores extra spaces when converting numbers with `%d`. To ignore spaces at the beginning of the line, you need to put a space before the `%c` conversion specifier. So the format string should be `" %c%d%d%d"` – user3386109 Mar 23 '20 at 17:17
  • 1
    To search for answers that discuss `fgets` and `sscanf` use the following search string `[c] fgets sscanf is:answer` – user3386109 Mar 23 '20 at 17:20
  • Aside: use `int c;` and parentheses for `while((c = getchar()) != EOF)`. What you wrote will be evaluated as `while(c = (getchar() != EOF))` which gives `c` the values `0` or `1`. – Weather Vane Mar 23 '20 at 17:23
  • Consider adding a code that you have written. So that others can suggest improvements rather than providing direct answer. – Utsav Chokshi Mar 23 '20 at 17:30

0 Answers0