我想从C语言的stdin(我的键盘)中读取几行,但是我无法做到这一点。
我的输入看起来像这样:
3
first line
second line
third line
有我的代码:
char input[2], s[200];
if (fgets(input, 2, stdin) != NULL) {
printf("%d\n", input[0]);
for (int i = 1; i <= input[0] - '0'; i++) {
if (fgets(s, 20, stdin) != NULL)
printf("%d\n", s[1]);
}
}
似乎该功能“ fgets”甚至在读取我的新行char(以ASCII编码的10)。顺便说一句,我正在Linux终端中运行我的代码。
我想从C语言的stdin(我的键盘)中读取几行,但是我无法做到这一点。
原因:
printf("%d\n", input[0]);
该语句将打印出额外的\n
,fgets
在第一次迭代时将读取该额外的。因此,s
将存储\n
在第一次迭代中。使用getchar()
读额外的\n
。
fgets(s, 20, stdin)
,你正在读取20个字节,但输入字符串(第二个)占用了20个字节以上。增加它。
printf("%d\n", s[1]);
改成 printf("%s\n", s);
代码是:
#include <stdio.h>
#include <string.h>
int main()
{
char input[2], s[200];
if (fgets(input, 2, stdin) != NULL)
{
printf("%d\n", (input[0]- '0'));
getchar(); // to read that extra `\n`
for (int i = 1; i <= (input[0] - '0'); i++)
{
if (fgets(s, 50, stdin) != NULL) // increase from 20 to 50
printf("%s\n", s); // printing string
}
}
return 0;
}
输出为:
3
3
this is first line
this is first line
this is the second line
this is the second line
this is the third line
this is the third line