我正在编写一个程序,它从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
关于如何将数字拉入正确数组的任何想法?
答案 0 :(得分:0)
这是一个解决方案:
#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;
}
答案 1 :(得分:0)
从您的问题来看,要读取数据,必须修改第一个循环
for (i = 0; i < cars; i++) {
fscanf(ifp, "%d", &START_BID[i]);
fscanf(ifp, "%d", &MIN_INCREASE[i]);
}
并将数据打印为单独的数组
printf("\nStarting Bids:\t");
for (i = 0; i < cars; i++) {
printf("%d\t", START_BID[i]);
}
printf("\nMinimum Increase:\t");
for (i = 0; i < cars; i++) {
printf("%d\t", MIN_INCREASE[i]);
}
printf("\n");
这样输出控制台看起来像
Starting Bids: 50 250 5 500 300
Minimum Increase: 40 140 6 50 200