[英]How to read integers from .txt file and store them in a integer type array in C
I have a file that contains integers separated with ' '
我有一个文件,其中包含用
' '
分隔的整数
Example File1示例文件 1
8 7 8 8 7 7 7
Example file2示例文件2
10 0 3 11 0 2 3 3 2 4 5 6 2 11
I want to read these integers and save them in an integer array.我想读取这些整数并将它们保存在一个整数数组中。
-->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}
I have done this code so far... Can anyone help here?到目前为止我已经完成了这段代码......有人可以帮忙吗?
#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;
}
Each time you read something from a file, the pointer moves one position.每次从文件中读取内容时,指针都会移动一个位置。 After you've read the file once to count the number of integers, the pointer is pointing to the end of the file.
在您读取文件一次以计算整数的数量后,指针指向文件的末尾。
You have to rewind your FILE pointer, so it goes back to the start and you can scan again to get the numbers.您必须倒回 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.