Note that there are some explanatory texts on larger screens.

plurals
  1. POWhile loop stuck waiting for input
    primarykey
    data
    text
    <p>I have a function that is trying to read each line of a file, then use sscanf to pass values into an array of structs, creating a new struct for each line of the file that is not a comment line containing char '#'. This is my code: </p> <pre><code>typedef struct { int row, col, C, D; char program[80]; } agentDetails; </code></pre> <p>My structs are defined in a header file, #included in the main file.</p> <pre><code>char currentLine[80]; char** agents; int n=0; agents = malloc(sizeof(char*)*4); while (fgets(currentLine, sizeof currentLine, file) != NULL) { if(!strchr(currentLine, '#')) { agentDetails agents[n]; /*create new struct in array agents*/ sscanf(currentLine, "%d %d %c %s %s", &amp;agents[n].row, &amp;agents[n].col, &amp;agents[n].C, agents[n].program, agents[n].D); n++; } } </code></pre> <p>this works, however when it reaches end of file it does not exit the loop, it sits there waiting for input. I have tried stepping through with gdb, after the last line it steps to the while(fgets...) line, and then waits for input. </p> <p>I know this code works if I try to sscanf values into variables initialised within the function, it only seems to fault when I use an array of structs. What is happening here?</p> <hr> <p>I have changed the code so it works, see below:</p> <pre><code>int n = 0; int i = 0; while (fgets(currentLine, sizeof currentLine, file) != NULL) { if(!strchr(currentLine, '#')) { n++; } } rewind(file); agentDetails agents[n]; while (fgets(currentLine, sizeof currentLine, file) != NULL) { if(!strchr(currentLine, '#')) { sscanf("same as above"); i++; } } </code></pre> <p>I dont use malloc, however. Is this a problem? Will this cause issues?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload