从C中的文本文件加载数字

我想从文本文件(.txt)中将已知数量的数字加载到C中的数组中。 格式为:

“0,1,2,5,4”

我是C的新手,有人可以推荐一种加载文本文件的方法吗?

干杯

使用fscanf可以轻松完成:

 #include  int main() { FILE* f = fopen("test.txt", "r"); int number = 0; int sum = 0; /* the sum of numbers in the file */ while( fscanf(f, "%d,", &number) > 0 ) // parse %d followed by ',' { sum += number; // instead of sum you could put your numbers in an array } fclose(f); } 

@pmg:当然,为什么不呢。 我只是如果它是一个hw,那么给出一个完整的解决方案是一件坏事:)

 #include  int main() { FILE* f = fopen("test.txt", "r"); int n = 0, i = 0; int numbers[5]; // assuming there are only 5 numbers in the file while( fscanf(f, "%d,", &n) > 0 ) // parse %d followed by ',' { numbers[i++] = n; } fclose(f); } 

您可以:

1)一次读取一个数字并使用atoi()转换为int

2)您可以一次读取整个数组并使用strtok分割数字,然后使用atoi()进行转换

这里有一个strtok的例子:

  int main(int argc, char *argv[]) { int x = 1; char str[]="this:is:a:test:of:string:tokenizing"; char *str1; /* print what we have so far */ printf("String: %s\n", str); /* extract first string from string sequence */ str1 = strtok(str, ":"); /* print first string after tokenized */ printf("%i: %s\n", x, str1); /* loop until finishied */ while (1) { /* extract string from string sequence */ str1 = strtok(NULL, ":"); /* check if there is nothing else to extract */ if (str1 == NULL) { printf("Tokenizing complete\n"); exit(0); } /* print string after tokenized */ printf("%i: %s\n", x, str1); x++; } return 0; 

Hy尝试这个。

 #include  #define MAX_NUMBERS 1000 /* Max numbers in file */ const char DATA_FILE[] = "numbers.dat"; /* File with numbers */ int data[MAX_NUMBERS]; /* Array of numbers */ int main() { FILE *in_file; /* Input file */ int middle; /* Middle of our search range */ int low, high; /* Upper/lower bound */ int search; /* number to search for */ char line[80]; /* Input line */ in_file = fopen(DATA_FILE, "r"); if (in_file == NULL) { fprintf(stderr,"Error:Unable to open %s\n", DATA_FILE); exit (8); } /* * Read in data */ max_count = 0; while (1) { if (fgets(line, sizeof(line), in_file) == NULL) break; /* convert number */ sscanf(line, "%d", &data[max_count]); ++max_count; return data; } return (0); } 

始终确保您从价值中读取的内容。 如果你正在从文件中读取字符确定。 但是如果你想读取整数,请务必将它们作为字符读取并将它们转换为整数。

 #include int main() { char a; FILE *point; int i, b[4]; point = fopen("test.txt", "r"); for(i = 0; i < 4; i++) { a = fgetc( point); b[i] = atoi(&a); } fclose(point); // printing put the values ,but i dont get the text file values for(i = 0; i < 4; i++) printf("%d\n" , b[i]); } 

这是我的文本文件,

 3210 

这是我的输出,

 3 2 1 0