我想弄明白,如何将多个字符串扫描到结构中的数组并打印出来。
我在循环中放了两张支票:
检查#1:工作正常。
检查#2:不工作。以某种方式将所有字符串放在for循环之后的一个数组中,而不是像在for循环中那样将它们分开。
检查#3:这也会产生与检查2相同的问题。
我应该声明另一个数组order_t items []来存储垃圾箱或我该怎么办?我完全糊涂了......
我正在尝试扫描如下
1000000 4
181 5c 915 4h 816 4g 716 10g
数字的含义:
(customer item_amount
bin_amount [0] bin [0],bin_amount [1] bin [1],.....等。)
源代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_ORDERS 100 /*maximum orders*/
#define MAX_ITEMS 10 /*maximum items in one order*/
#define BIN_CODE 2 /*maximum string for bin*/
/*struct 1: collect order number and item amount*/
typedef struct {
int customer;
int item_amount;
char bin[MAX_ITEMS][BIN_CODE];
int bin_amount[MAX_ITEMS];
}order_t;
/*general function titles*/
void print_title(int stage);
int read_order(order_t orders[]);
/*main program*/
int
main(int argc, char *argv[]) {
order_t orders[MAX_ORDERS];
/*obtain the data*/
read_order(orders);
/*check 3: if it prints*/
printf("check3: %s\n", orders[0].bin[0]);
return 0;
}
/*2: scanf file*/
int
read_order(order_t orders[]){
int n=0, i;
order_t new;
while ((scanf("%7d %d\n",
&new.customer,
&new.item_amount)!=EOF) && (n<MAX_ORDERS)){
for (i=0; i<new.item_amount; i++){
scanf("%d %s ",
&new.bin_amount[i], new.bin[i]);
/*check 1: if it print correctly within the for loop*/
printf("check 1: %s\n", new.bin[i]);
}
scanf("\n");
orders[n] = new;
n += 1;
}
/*check 2: if it print as an array outside of for loop*/
printf("check 2: %s\n", orders[0].bin[0]);
return n;
}
结果如下:
check 1: 5c
check 1: 4h
check 1: 4g
check 1: 10g
check 1: 1a
check 1: 1c
check 1: 2a
check 1: 2f
check 1: 1d
check 2: 5c4h4g10g
check3: 5c4h4g10g