我试图从文件file.txt中获取所有整数,并将它们放入动态分配的数组中。但是,该文件也可以包含其他字符,这些字符不应放入数组中。
文件包含以下内容:
2-34 56-2342344
12示例-34en+56ge-tal345
int* getIntegers(char* filename, int* pn)
{
FILE* fileInput = fopen(filename, "r");
int* temp = (int*)malloc( 100*sizeof(int));
int counter = 0;
int c= fgetc(fileInput);
while(c != EOF){
counter ++;
printf("%d;\t%d\n", counter, c);fflush(stdout);
temp[counter++] = c;
}
*pn = counter;
return (temp);
}
int main(void)
{
int n;
int* a = getIntegers("file.txt", &n);
if (a != NULL){
puts("numbers found:");
for (int i = 0;i < n; i++){
printf("%d ",a[i]);
}
free(a);
}
putchar('\n');
while(getchar()== '\n');
return (EXIT_SUCCESS);
}
运行此命令时,将返回以下输出:
输出:
1; 49
3; 49
5; 49
7; 49
9; 49
11; 49
13; 49
15; 49
17; 49
19; 49
21; 49
而正确的输出应该是
找到的号码:
12 -34 56 23423424 12 -34 56 345
最佳答案
试试这个
#include <stdlib.h>
#include <stdio.h>
int* getIntegers(char* filename, int* pn)
{
int* temp = (int*)malloc( 100*sizeof(int));
int counter = 0;
int result;
int c;
FILE* fileInput = fopen(filename, "r");
if ( fileInput == NULL) {
return temp; // return if file open fails
}
while( 1) {
result = fscanf (fileInput, "%d", &c);//try to read an int
if ( result == 1) { // read successful
temp[counter] = c; //save int to array
counter++;
printf("%d;\t%d\n", counter, c);
}
else { // read not successful
fscanf ( fileInput, "%*[^-+0-9]"); //scan for anything not a -, + or digit
}
if ( counter > 98) { // dont exceed array
break;
}
if ( feof( fileInput)) { // check if at end of file
break;
}
}
fclose ( fileInput); // close the file
*pn = counter;
return (temp);
}
int main(void)
{
int n;
int i;
int* a = getIntegers("file.txt", &n);
if (a != NULL){
printf("numbers found:");
for (i = 0;i < n; i++){
printf("%d ",a[i]);
}
free(a);
}
putchar('\n');
return (EXIT_SUCCESS);
}