#include <stdio.h>
int getIntegers(char *filename,int a[]);
int main(void) {
/////
FILE *fp;
char file[10] = "random.txt";
fp = fopen(file, "w");
fprintf(fp, "1 2 -34 56 -98 42516547example-34t+56ge-pad12345\n");
fclose(fp);
/////
int i;
int a[100];
int n = getIntegers(file,a);
//Here i want to print out what i got from getIntegers. What it should put out = "1 2 -34 56 -98 42516547 -34 56 12345"
if (n > 0)
{
puts("found numbers:");
for(i = 0;i < n; i++)
{
printf("%d ",a[i]);
}
putchar('\n');
}
return 0;
}
int getIntegers(char *filename, int a[])
{
int c, i;
FILE *fp;
fp = fopen(filename, "r");
//I want what this code does to be done with the commented code under it. This will give "1 2 -34 56 -98 42516547"
while (fscanf(fp,"%d",&i)==1)
{
printf("%d ",i);
}
fclose(fp);
// I want this code to give "1 2 -34 56 -98 42516547 -34 56 12345"
// while ((c = fgetc(fp)) != EOF)
// {
// for(i = 0; i < c;i++)
// {
// fscanf(fp, "%1d", &a[i]);
// }
// }
// return i;
}
ファイルに数字と単語/文字があります。このコードでは、最初の文字まで整数を取得しますが、EOFまで続行します。そして、それらの数字を返して、メインでそれらを印刷します。私は試しましたが、うまく動作しませんでした。これを行うにはどうすればよいでしょうか?または私は何が間違っている。ファイルを読み込み、整数だけを取得して終了まで続きます
は 'getIntegersをint型()'任意の値を返しません。コードは 'a []'に何も保存しません。 – chux