gpt4 book ai didi

c - 尝试将数字存储在数组中并通过从文件中读取来显示它们

转载 作者:太空宇宙 更新时间:2023-11-04 07:31:36 24 4
gpt4 key购买 nike

我试图只从名为 Store-1.txt 的文件中读取数字。此文件包含以下内容:“coffee 3Mugs -3Soap 10”
我正在使用 fscanf() 函数而不是 getc()。我的代码无法编译。我哪里错了。 PS:我是C新手,请耐心等待。

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a[20];
int i,j;


FILE *fp;
fp=fopen("C:/Users/PSN/Desktop/Store-1.txt","r");
if(fp>0)
{
for(i=0;i<4;i++)
{
fscanf(fp,"%d",&a[i])
}
}
for(j=0;j<3;j++)
{
printf("%d", a[j]);
}

fclose(fp);

system("PAUSE");
return 0;
}

最佳答案

如果您的输入文件“store-1.txt”如下所示:

coffee 3
Mugs -3
Soap 10

然后试试这个:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int a[20];
int i;

FILE *fp;
fp=fopen("store-1.txt","r");

if(fp>0) {
for(i=0;i<3;i++) {
fscanf(fp,"%*s %d", &a[i]);
}
}
for(i=0;i<3;i++) {
printf("%d\n", a[i]);
}

fclose(fp);

return 0;
}

应该让你朝着正确的方向前进......

注意 %*s 告诉 fscanf 有一个字符串但是要忽略它

预期输入的替代方案:

coffee 3Mugs -3Soap 10

可能是:

int main()
{
int a[20];
int i,j;

FILE *fp;
fp=fopen("store-1.txt","r");

fscanf(fp, "%*s%d%*s%d%*s%d", word, &a[0], word, &a[1], word, &a[2]);

/* if(fp>0) { */
/* for(i=0;i<3;i++) { */
/* fscanf(fp,"%s %d",word, &a[i]); */
/* } */
/* } */
for(j=0;j<3;j++) {
printf("%d\n", a[j]);
}

fclose(fp);

return 0;
}

这对您的输入文件有效,但可能无法像您希望的那样扩展?

关于c - 尝试将数字存储在数组中并通过从文件中读取来显示它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13277009/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com