Search code examples
cinputstdin

How to read 2 lines of integer input in C?


I'm doing a project for my algorithms class and I'm having a lot of trouble with inputs. I'm trying to read an input like this:

6 0 2 3 1 3
5 9 2 1 3

The integers will need to go to

int num1; // num1 = 6
int num2; // num2 = 5
int array1[100]; // array1 = {0, 2, 3, 1, 3, 0, 0, ...}
int array2[100]; // array2 = {9, 2, 1, 3, 0, 0, ...}

The input will come from standard input, in the form of a file. So in terminal running the program would look like this:

cat input.txt | ./a.out

Where input.txt contains the two lines of integers.

Here is my flawed attempt so far:

while(scanf("%d%c", &temp, &ch) > 1){
    if (ch != '\n'){
        one[count] = temp;
    } 
    else if (ch == '\n'){
        count = 0;
        two[count] = temp;

    }
    one[count] = temp;
    count++;
    if (ch != ' ')
    {
        printf("Invalid input. Please do int + space.\n");
        return -1;
    }
    if ((temp >= 100) || (temp <= -100))
    {
        printf("Input is too big, must be between -100, 100.\n");
        return -1;
    }
    if (one[0] < 1){
        printf("Input for n cannot be smaller than one!");
        return -1;
    }
}

I think the main issue is that I'm just not sure how to deal with multiple lines of input. One line of input is fine by me but multiple lines is what trips me over.


Solution

  • You could fetch an entire line of input using the getline function and then iterate over that line, scanning one number at a time using the strtol function.

    From the example in your question I assume that you want all remaining entries in the two arrays to be zero so don't forget to zero them out (either manually or using the memset function.).

    And also don't forget to free() the buffer getline gave you.