gpt4 book ai didi

c - 如何从.txt文件中读取整数并将它们存储在C中的整数类型数组中

转载 作者:行者123 更新时间:2023-11-30 19:07:21 25 4
gpt4 key购买 nike

我有一个文件,其中包含用 ' ' 分隔的整数

示例文件1

8 7 8 8 7 7 7

示例文件2

10 0 3 11 0 2 3 3 2 4 5 6 2 11

我想读取这些整数并将它们保存在整数数组中。

   -->int array[for example File1]={8,7,8,8,7,7,7}
-->int array[for example File2]={10,0,3,11,0,2,3,3,2,4,5,6,2,11}

到目前为止我已经完成了这段代码...有人可以帮忙吗?

#include <stdio.h>
int main() {
FILE *f1;
int i,counter=0;
char ch;
f1 = fopen("C:\\Numbers.txt","r");

while((ch = fgetc(f1))!=EOF){if(ch==' '){counter++; }}
int arMain[counter+1];

for(i=0; i<counter+1; i++) {
fscanf(f1, "%d", &arMain[i]);
}

for(i = 0; i <= counter+1; i++) {
printf("\n%d",arMain[i]);
}

return 0;
}

最佳答案

每次从文件中读取内容时,指针都会移动一个位置。读取文件一次并计算整数个数后,指针将指向文件末尾。

您必须倒回 FILE 指针,以便它返回到开头,您可以再次扫描以获取数字。

#include <stdio.h>

int main(){
FILE *f1;
int i,counter=0;
char ch;
f1 = fopen("nums.txt","r");

while((ch = fgetc(f1))!=EOF){if(ch==' '){counter++; }}
int arMain[counter+1];

rewind(f1); /* Rewind f1 */
for(i=0; i<counter+1; i++) {
fscanf(f1, "%d", &arMain[i]);
}

for(i = 0; i <= counter+1; i++) {
printf("\n%d",arMain[i]);
}

return 0;

}

关于c - 如何从.txt文件中读取整数并将它们存储在C中的整数类型数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46935487/

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