gpt4 book ai didi

c - 从文件中获取数字并将它们放入数组中需要的建议

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

我正在编写一个程序,从 txt 文件中获取数字并将它们放入 2 个不同的数组中。

文本文件如下所示:

    50 40
250 140
5 6
500 50
300 200

我需要将第一列中的所有数字放入一个数组中,将第二列中的所有数字放入另一个数组中。

到目前为止,这是我的代码:

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

int main()
{
FILE * ifp = fopen("input2.txt","r"); //Open the input file
int cars = 5, i , j; // Initialized cars and counters i and j
char VIEW[20], BID[20], CLOSE[20];
int CAR[10], START_BID[10], MIN_INCREASE[10];
int *b; // Temp pointer to current bid
int *m; // Temp pointer to current array of the minimum increase

strcpy(VIEW, "VIEW");
strcpy(BID, "BID");
strcpy(CLOSE, "CLOSE");

for (i = 0; i < cars; i++) {
b = &START_BID[i]; // Get pointer to current START_BID
m = &MIN_INCREASE[i]; // Get pointer to array of current MIN_INCREASE
fscanf(ifp, "%d", &b[i]);
for (j = 0; j < cars; j++) {
fscanf(ifp, "%d", &m[i]);
}
}

printf("%d\n", START_BID);
printf("%d\n", MIN_INCREASE);

fclose(ifp);

return 0;
}

我让它打印 2 个数组的内容以查看它们是否被正确拉取。

这是我的输出:

    2686588
2686548

关于如何将数字放入正确的数组有什么想法吗?

最佳答案

这是一个解决方案:

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

int main()
{
FILE * ifp = fopen("file.txt","r"); //Open the input file
int cars = 5, i , j; // Initialized cars and counters i and j
char *view="VIEW", *bid="BID", *CLOSE="CLOSE";
int CAR[10], START_BID[10], MIN_INCREASE[10];

for (i = 0; i < cars; i++)
{
fscanf(ifp, "%d %d", &START_BID[i],&MIN_INCREASE[i]);
}

for (i = 0; i < cars; i++)
{
printf("%d %d\n", START_BID[i], MIN_INCREASE[i]);
}
fclose(ifp);
return 0;
}

关于c - 从文件中获取数字并将它们放入数组中需要的建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15844447/

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