我试图在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);
}
但是,当它到达最后一行时,它会不停地打印出来,而不会终止。如有任何指导,将不胜感激。
发布于 2016-02-06 18:35:31
既然您提到了换行,我假设您的数据是文本。这里有一个方法,当你知道线的长度。fgets
也读取newline
,但这很容易被忽略。我没有尝试使用feof
,而是简单地检查fgets
的返回值。
#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;
}
程序会话(在Windows控制台中由Ctrl结束,在Linux中由Ctrl结束)
qwertyuiop
113 119 101 114 116 121 117 105 111 112
asdfghjkl;
97 115 100 102 103 104 106 107 108 59
zxcvbnm,./
122 120 99 118 98 110 109 44 46 47
^Z
https://stackoverflow.com/questions/35244547
复制相似问题