我正在尝试编写一个使用fgets接收字符串的程序,但是由于某些原因,我无法使它超出用户输入阶段。一旦用户输入“空白”,即应停止输入。 Enter键(\ n),但即使按下此键,循环仍会继续。
这是我的代码中有问题的部分:
char array[100][256];
for (int i = 0; array[i] != '\n'; i++)
{
fgets(array[i], 256, stdin);
}
100和256分别代表预期的最大行数和字符数。
有人知道我哪里出了问题吗?
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 */ }