我知道如何通过使用 fopen、fgets 等读入 FILE* 来逐行循环文件 但是我如何使用纯 C 逐行查看 char 数组? 我在谷歌上搜索了很多,但只能找到从文件中读取的内容。
最佳答案
#include <stdio.h>
char *sgets(char *s, int n, const char **strp){
if(**strp == '\0')return NULL;
int i;
for(i=0;i<n-1;++i, ++(*strp)){
s[i] = **strp;
if(**strp == '\0')
break;
if(**strp == '\n'){
s[i+1]='\0';
++(*strp);
break;
}
}
if(i==n-1)
s[i] = '\0';
return s;
}
int main(){
const char *data = "abc\nefg\nhhh\nij";
char buff[16];
const char **p = &data;
while(NULL!=sgets(buff, sizeof(buff), p))
printf("%s", buff);
return 0;
}
关于c - 逐行循环遍历 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20299987/