我试图从文件file.txt中获取所有整数,并将它们放在动态分配的数组中。但是,该文件也可能包含其他字符,这些字符不应放在数组中。
该文件包含以下内容:
2 -34 56 - 23423424 12example-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
答案 0 :(得分:2)
该计划有很多问题。
fclose()
关闭它。答案 1 :(得分:1)
代码中有很多循环漏洞。您需要先修复它。
int c= fgetc(fileInput);
while(c != EOF)
{
counter ++;
printf("%d;\t%d\n", counter, c);fflush(stdout);
temp[counter++] = c;
}
这段代码让我发疯。通过从文件中只读取一个字符并在循环中运行而获得的是什么?有机会读取另一个字节。
必须检查返回值fopen
函数。如果文件不存在或打开错误怎么办?你的节目疯狂了。所以确保
FILE* fileInput = fopen(filename, "r");
if(fileInput==NULL ){
printf("Error to open file\n");
return
}
此外,你在循环中递增计数器两次,第一次是counter ++;
,第二次是temp[counter++] = c;
这是管理数组索引的错误。
最重要的是每个打开的文件都必须关闭。
答案 2 :(得分:1)
试试这个
#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);
}