【发布时间】:2013-11-23 17:32:55
【问题描述】:
我必须制作一个程序,将 a 和 b 作为输入,将以下形式的行数“a”作为输入:“studentId studentName studentPhone”和 b 行以“stId mark1 mark2”的形式输入标记 3"。然后程序从第一个输入中输出所有 stid,如果输入 b 中存在相同的 id,则程序输出除其 id 之外的学生分数。
我经历了地狱般的正确输入,我认为这很接近但我得到了一个奇怪的行为:在我在第二个输入中输入标记后,似乎第一个输入中的一些学生 ID 已更改.
这是我的代码:(这里我尝试只输入学生 ID。http://ideone.com/dBYzwe)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
void chomp(char *s);
struct listA{
int stId;
char stName[19];
char stPhone[12];
};
struct listB{
int stId;
char marks[11];
};
int main(void) {
int i, j, m, n;
scanf("%d%d", &m, &n);
struct listA *a = malloc(sizeof(m * sizeof(struct listA)));
struct listB *b = malloc(sizeof(n * sizeof(struct listB)));
for(i = 0; i < m; i++)
{
scanf("%d", &a[i].stId);
fgets(a[i].stName, 19, stdin);
fgets(a[i].stPhone, 11, stdin);
chomp(a[i].stName);
chomp(a[i].stPhone);
}
for(i = 0; i < m; i++)
printf("%d ", a[i].stId);
for(i = 0; i < n; i++)
{
scanf("%d ", &b[i].stId);
fgets(b[i].marks, 12, stdin);
fflush(stdin);
}
printf("\n");
for(i = 0; i < n; i++)
{
printf("%d ", b[i].stId);
}
printf("\n");
for(i = 0; i < m; i++)
printf("%d ", a[i].stId);
return 0;
}
void chomp(char *s) {
while(*s && *s != '\n' && *s != '\r') s++;
*s = 0;
}
【问题讨论】:
-
a不是数组,那你为什么用a[i]? -
您使用的是 MS Windows 吗?你使用的是哪个编译器?
-
我忘记将 sizeof 与 m 和 n 相乘,所以它们都是数组。我只是这样做了,在我获得第二个输入后它仍然会更改第一个输入的值
-
@hacks 我在 Windows 上,但我在 ideone.com 上运行它(查看链接)
-
使用
fflush(stdin);(MS DOS 除外)将调用未定义的行为。