gpt4 book ai didi

c - 在 C 中循环 stdin

转载 作者:行者123 更新时间:2023-11-30 15:12:09 25 4
gpt4 key购买 nike

我正在尝试循环标准输入,但由于我们无法知道标准输入的长度,我不确定如何创建循环或在其中使用什么条件。

基本上我的程序将通过管道传输一些数据。数据中的每一行包含 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);

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

我已经尝试过

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

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

最佳答案

既然你提到换行符,我假设你的数据是文本。当您知道线路长度时,这是一种方法。 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;
}

程序 session (在 Windows 控制台中由 Ctrl-Z 结束,在 Linux 中由 Ctrl-D 结束)

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

关于c - 在 C 中循环 stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35244547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com