我需要编写一个程序,从stdin读取数据,并且只将非空行写入stdout(即只包含\n的行)。例如,如果stdin是:
1
2
\n
3
结果将是:
1
2
3
这就是我目前所拥有的:
#include <stdio.h>
#include <string.h>
int main()
{
char buf[BUFSIZ];
char *p;
printf ("Please enter some lines of text\n");
if (fgets(buf, sizeof(buf), stdin) != NULL)
{
printf ("%s\n", buf);
/*
* Remove newline character
*/
if ((p = strchr(buf, '\n')) != NULL)
*p = '\0';
}
return 0;
}
有没有什么方法可以循环程序,这样即使输入了一个空行,用户仍然可以继续输入?
最佳答案
#include <stdio.h>
int main(void){
char buf[BUFSIZ];
printf ("Please enter some lines of text\n");
while(fgets(buf, sizeof(buf), stdin) != NULL){
if(*buf != '\n')
printf("%s", buf);
}
return 0;
}
关于c - 验证空行的输入(\n\n),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10343438/