[英]copying text to a character array from a text file in C?
Hey there, How do I go about copying text inside a text file into a multidimensional character array? 嘿,如何将文本文件中的文本复制到多维字符数组中?
supposing the text file( text_file.txt) contained 假设包含的文本文件(text_file.txt)
this is the first line
这是第一行
this is the second line
这是第二行
this is the third line
这是第三行
#include <stdio.h>
int main(void){
FILE *f;
f=fopen("text_file.txt","r");
if (f==NULL){
printf("invalid!");
return 1;
}
else {
printf("successful");
}
char copied_text[80][80];
while (!feof(f)){
int i=0,j=0;
fgets(copied_text[i][j],"%s",f);
i++;
}
return 0;
}
-thank you. -谢谢。
I think your code almost work. 我认为您的代码几乎可以正常工作。
Just move the declaration of int i out of the loop. 只需将int i的声明移出循环即可。
Change the first parameter of fgets to copied_text[i] because it needs a pointer here. 将fgets的第一个参数更改为copyed_text [i],因为这里需要一个指针。
Change the second parameter of fgets to 80 because it should be a int indicates the acceptable string length. 将fgets的第二个参数更改为80,因为它应该为int表示可接受的字符串长度。
#include <stdio.h>
int main(void){
FILE *f;
f=fopen("text_file.txt","r");
if (f==NULL){
printf("invalid!\n");
return 1;
}
else {
printf("successful\n");
}
char copied_text[80][80];
int i=0;
while (!feof(f)){
fgets(copied_text[i],80,f);
++i;
}
for(int i = 0; i <3; ++i)
printf("%s\n", copied_text[i]);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.