Home > front end >  How to use scanf or use a different input reading method?
How to use scanf or use a different input reading method?

Time:10-02

Newcomer to C here and struggling a bit.

I'm reading input that looks like this:

9, 344, 100
10, 0, 469
...

I am trying to group each line so that I can send each 3 numbers as parameters in a function.

I have been trying to use scanf but because it maps to memory addresses, I am having a problem with retaining the numbers after each line. I don't know how many lines of data I will have so I cannot make a certain number of arrays. Also, I am limited to functions in <stdio.h>.

If I use scanf is there anyway for me to avoid using malloc?

I have attached an idea below. Looking for suggestions and maybe some clarification on how scanf works.

Apologies if I'm missing something obvious here.

int main() {
  int i = 0;
  int arr[9]; //9 is just a test number to see if I can get 3 lines of input
  char c;
  while ((c = getchar()) != EOF) {
    scanf("%d", &arr[i]);
    scanf("%d", &arr[i   1]);
    scanf("%d", &arr[i   2]);
    printf("%d, %d, %d\n", arr[i],
      arr[i   1], arr[i   2]); //serves only to check the input at this point
      //at this point I want to send arr 1 to 3 to a function
    i  = 3;
  }
}

The output of this code is a bunch of memory addresses and some of the correct values interspersed. Something like this:

0, 73896, 0
0, 100, -473670944

When it should read:

0, 200, 0
0, 100, 54
int main(){
    char c;
    while ((c=getchar()) != EOF){
        if (c != '\n'){
            int a;
            scanf("%d", &a);
            printf("%d ", a);
        }
        printf("\n");
    }
}

This code prints out the input correctly, but doesn't allow me to use scanf more than once in the while block without a memory problem.

CodePudding user response:

One option is to scan all three at the same time. You also need to match the commas (,) in the input.

Example:

#include <stdio.h>

int main() {
    int arr[9];

    int i = 0;
    for(; i   3 <= sizeof arr / sizeof *arr // check that there is room in "arr"
          &&                               // and only then, scan:
          scanf(" %d, %d, %d", &arr[i], &arr[i 1], &arr[i 2]) == 3;
          i  = 3)
    {
        printf("%d, %d, %d\n", arr[i], arr[i 1], arr[i 2] );
    }
}

CodePudding user response:

I would rather use fgets and sscanf for that.


char buff[64];

/* .......... */

if(fgets(buff, 63, stdin) != NULL)
{
    if(sscanf(buff, "%d,%d,%d", &arr[i], &arr[i   1], &arr[i   2]) != 3)
    {
        /* handle scanf error */
    }
}
else
{
    /* handle I/O error / EOF */
}
  • Related