简体   繁体   中英

How to read into array of strings using gets?

I have an array of 15 strings (which don't all have to necessarily be used), and despite reading everywhere that gets should never be used, for some reason I believe it is most convenient for me for this program. After prompting the user to specify how many rows and columns he wants, to create a matrix, I ask him to enter the matrix values, one row per line at a time. I do this using gets . Simultaneously, I want to scan through the string for the amount of spaces entered to ensure that the user is entering the appropriate amount of numbers that correspond to the amount of columns specified.

At the end I want to print out the second row that I entered.

You can assume rowone and colone are already defined, I just didn't copy that part of the code to save space.

int i=0, rowone, colone, sbar=0, inputs=0;
char matrixone[15][10000];
 ......

printf("input your matrix\n");

for (i=0;i<rowone;i++){
    gets(matrixone[i]);

    while(matrixone[i][inputs]!='\n'){
        if (mplier[i][inputs] == ' '){
        sbar++;
        inputs++;
        }
        else
        inputs++;

    }
    if (sbar>=colone||sbar<colone-1){
            printf("Too many/too few inputs per line\n");
            main();
        }

  sbar = 0;
  inputs = 0;

  }
  puts(matrixone[2])

I get warnings when compiling and ultimately not even the chance to input the matrix as "Too many/too few inputs" always pops up.

Any help would be greatly appreciated, thank you!

Infinite loop.

Or more properly, eventually matrixone[i][inputs] accesses way beyond what it was read and maybe beyond the array itself. This leads to undefined behavior (UB).

gets() consumes, but does not save '\\n' .

gets(matrixone[i]);
while(matrixone[i][inputs]!='\n'){  // why should this quit?
  ...
  inputs++;
}

Instead, drop gets() as it is dropped from the language for 5 years now, use fgets() , check return value and look for the end of the string as well

if (fgets(matrixone[i], sizeof matrixone[i], stdin) {
  while(matrixone[i][inputs] != '\0'){
    ...
  }
}

Suggestion for OP (guessing OP's goal)

char *matrixone[15] = { 0 };
printf("input your matrix\n");

for (i=0;i<min(rowone,15);i++){
  buf[1000];
  if (fgets( buf, sizeof buf, stdin) == NULL) break;
  buf[strcspn(buf, "\n")] = 0;

  // qualify buf concerning ' ' , sbar, etc
  ...

  matrixone[i] = strdup(buf);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM