在C中循环stdin

时间:2016-02-06 18:09:17

标签: c

我试图遍历stdin,但由于我们无法知道stdin的长度,我不知道如何创建循环或在其中使用什么条件。

基本上我的程序将通过管道传输一些数据。数据中的每一行包含10个字符的数据,后跟换行符(每行11个字符)

在伪代码中,我想要完成的是:

while stdin has data:
    read 11 characters from stdin
    save 10 of those characters in an array
    run some code processing the data
endwhile

while循环的每个循环将数据重写为相同的10个字节的数据。

到目前为止,我已经找到了

char temp[11];
read(0,temp,10);
temp[10]='\0';
printf("%s",temp);

将从stdin获取前11个字符,然后保存。 printf稍后将被更多分析数据的代码所取代。但我不知道如何将这个功能封装在一个循环中,该循环将处理来自stdin的所有数据。

我试过了

while(!feof(stdin)){
    char temp[11];
    read(0,temp,11);
    temp[10]='\0';
    printf("%s\n",temp);
}

但是当它到达最后一行时,它会反复打印出来而不会终止。任何指导都将不胜感激。

1 个答案:

答案 0 :(得分:1)

由于您提到换行符,我假设您的数据是文本。当你知道线长时,这是一种方法。 $('.save-hidden').animate({ opacity: 0 }, { complete: function() { alert('Executes now.'); }, duration : 2000 }); 也会读取fgets,但这很容易被忽略。我只是检查newline的返回值,而不是尝试使用feof

fgets

程序会话(在Windows控制台中以Ctrl-Z结束,在Linux中以Ctrl-D结束)

#include <stdio.h>

int main(void) {
    char str[16];
    int i;
    while(fgets(str, sizeof str, stdin) != NULL) {  // reads newline too
        i = 0;
        while (str[i] >= ' ') {                     // shortcut to testing newline and nul
            printf("%d ", str[i]);                  // print char value
            i++;
        }
        printf ("\n");
        str[i] = '\0';                              // truncate the array
    }
    return 0;
}