Reputation: 1
I'm trying to write a program that receives strings using fgets, but for some reason I can't get it to go past the user input stage. The input should stop once the user enters a "blank line", ie. the Enter key (\n) but even when this key is pressed the loop continues.
Here's the problematic part of my code:
char array[100][256];
for (int i = 0; array[i] != '\n'; i++)
{
fgets(array[i], 256, stdin);
}
100 and 256 represent the maximum amount of lines and chars expected respectively.
Does anyone know where I went wrong?
Upvotes: 0
Views: 593
Reputation: 62797
Here is your code fixed with minimal changes, explanations in comments. Note that this is not a very good way to solve your problem, long lines for example may not behave as you want (they will get split at several array
lines).
char array[100][256];
memset(array, 0, sizeof array); // initialize the memory
int i = 0;
while(i<100) // avoid overflow of lines, also while may be clearer than for loop
{
if(!fgets(array[i], 256, stdin)) break; // detect read failure
if(array[i][0] == '\n') break; // got empty line
// Note [0] above to test first char of line i
++i;
}
if (i==100) { /* too many lines */ }
else if (array[i][0] == 0) { /* read failure */ }
else { /* indexes 0...i-1 contain data, index i contains empty line */ }
Upvotes: 1