【发布时间】:2019-08-11 20:18:24
【问题描述】:
我现在正在学习结构,它们在我的脑海中很有意义,但我很难与它们一起工作。我正在使用重定向的标准输入('
2 2
6 1
7 4
8 2
8 9
我通过a.out < input.txt运行它
#include <stdio.h>
#include <stdlib.h> // for malloc() and exit()
struct arrival_struct
{
int time; // time of arrival
int count; // number of passengers/seats arriving
};
int main(void) {
struct arrival_struct arrivals;
int *time[10]; // stores # of batches for passenger arriving at the same time
int code;
int totalPassenger=0;
int i;
int *a; //dynamic memory base address
int required[10]; // stores # of passenger arrive at the same time in batch
int j=0;
// read in code until eof
while (scanf("%d", &code) !=EOF) {
//load the first token into time[j]
scanf("%d", *time[j]);
*time[j] = arrivals.time;
//load the second token into required[j]
scanf("%d", required[j]);
required[j] = arrivals.count;
//increment totalPassenger by the count token that was read in
totalPassenger = totalPassenger + required[j];
a=(int *)malloc(sizeof(int)*required[j]); //required[j] should be the number of passengers for that row
scanf("%i %i", a->time, a->count);
j++;
}
printf("total passengers: %d", totalPassenger);
}
我想这里有很多语法错误,因为我对 C 不是很熟悉,只是在参加研讨会。让我感到困惑的主要事情是从文件中读取它并确保您最终获得所需的
结构time: 2 count: 2 totalPassengers: 2
time: 6 count: 1 totalPassengers: 3
etc ..
抱歉,如果这很难理解,我对这门语言非常陌生,正在努力赶上我的同龄人。如果我的问题不清楚,请给我链接或解释一个简单的从标准输入读取并填充结构的方法。
编辑:
struct arrival_struct {
int time;
int count;
};
int main(void) {
int code;
int totalPassenger=0;
struct arrival_struct arrivals[10];
int i=0;
int j;
while (scanf("%d", &code) !=EOF) {
scanf("%d%d", arrivals[i].time, arrivals[i].count);
totalPassenger += arrivals[i].count;
i++;
}
printf("total passengers: %d", totalPassenger); //works
for (j=0;j<5;j++)
printf("time: %d\tcount: %d\n", arrivals[j].time, arrivals[j].count);
}
【问题讨论】:
-
我不明白这个问题。
-
@Joshua 我的问题是如何从标准输入读取结构,然后我可以对其进行一些操作,例如求和。我知道这不是很清楚抱歉!