Ania
Ania

Reputation: 450

C: Reading multiple values with scanf and saving them into an array

I found an answer to the first part of my question (how to read multiple values with scanf) but it doesn't seem to work for me (I think it's because of putting the values into an array and maybe also because I'm checking if the values given are 6 ints for sure):

I am writing a program that stores co-ordinates of 4 triangles in an array. Each line has 6 values and stores co-ordinates of one triangle. I want to read 6 co-ordinates at one time and do this operation for 4 triangles separately.

int tab[4][6];

for (int i = 0; i < 4; i++){
    while (scanf("%d %d %d %d %d %d", &tab[i][0], &tab[i][1], &tab[i][2], &tab[i][3], &tab[i][4], &tab[i][5]) != 6){
        printf("Error, try again: ");
        while (getchar() != '\n'){}
    }
}

So for example if first triangle's co-ordinates are (2,1), (5,6), (2,7), then I want to type in: "2 1 5 6 2 7" and as a result I want it to fill the first line of the array with the said numbers in the order I typed them in.

Obviously it doesn't work, the program stops working (not finishes the work, it stops) after the first line is given.

I get this error after debugging (after giving first line): "Unhandled exception at 0x0FDCC28C (msvcr120d.dll) in xxx.exe: 0xC0000005: Access violation writing location 0xCCCCCCCC."

How to fix it?

Upvotes: 3

Views: 2163

Answers (2)

Anders Cedronius
Anders Cedronius

Reputation: 2076

You need to subtract the pointer i when detecting input error like this for example ->

#include <stdio.h>
int main(int argc, const char * argv[]) {
    int tab[4][6];
    for (int i = 0; i < 4; i++){
        printf("Enter 6 values \n");
        int retVal=scanf("%d %d %d %d %d %d", &tab[i][0], &tab[i][1], &tab[i][2], &tab[i][3], &tab[i][4], &tab[i][5]);
        if (retVal == 6) {
            printf("You did enter -> %d %d %d %d %d %d\n",tab[i][0],tab[i][1],tab[i][2],tab[i][3],tab[i][4],tab[i][5]);
        } else {
            printf("Error entering values.. (Enter numbers). \n");
            while (getchar() != '\n'){}
            i--;
        }
    }
    return 0;
}

Upvotes: 4

chux
chux

Reputation: 153478

Unclear why OP's code failed without posting input used and prior code.


How to fix it?

Use fgets() to read a line of user input. Avoid mixing scanf() with fgets() in prior code. Then parse the buffer. Use " %n" at the end to look for success and extra text.

int tab[4][6];
char buf[6*12 * 2];  // Use a buffer twice expected max needs

for (int i = 0; i < 4; i++) {
  while (1) {
    if (fgets(buf, size  buf, stdin) == NULL) {
      return "Failed to read enough data"; // Handle end-of-file in some fashion
    }
    int n = 0;
    sscanf(buf, "%d%d%d%d%d%d %n", 
        &tab[i][0], &tab[i][1], &tab[i][2], &tab[i][3], &tab[i][4], &tab[i][5], &n);
    if (n > 0 && buf[n] == 0) {
      break;  // Success!
    }
    printf("Error - bad input, try again: ");
  }
}

Upvotes: -1

Related Questions