#include <stdio.h>
struct agent
{
char name[30];
int age;
} list[20];
main()
{
struct agent getData();
char ch;
int i = 0;
int j;
puts("1. Enter More");
puts("2. Display");
puts("3. Exit");
while ((ch = getchar()) < '3')
{
if (ch == '1')
{
list[i++] = getData();
}
else if (ch == '2')
{
for (j = 0; j < i; j++)
{
puts(list[j].name);
printf("%d\n", list[j].age);
}
}
puts("1. Enter More");
puts("2. Display");
puts("3. Exit");
}
}
struct agent getData(
{
struct agent tmp;
puts("Enter name");
scanf(" %s",tmp.name);
puts("Enter age");
scanf("%d",&tmp.age);
return tmp;
}产出:
1. Enter More
2. Display
3. Exit
1
Enter name
ace
Enter age
23
1. Enter More
2. Display
3. Exit
1. Enter More
2. Display
3. Exit
3为什么这些语句"1。输入更多的2。显示3。退出“被重复??
发布于 2013-10-12 19:00:11
getData()不会在输入后使用换行符。因此,它将在下一次getchar()调用中使用。由于\n“小于”int文字'3'的ascii值,而不是'1'或'2',所以您的菜单再次打印。
您可以通过多种方法解决这一问题,包括让getData()使用整行(包括换行符),或者使main中的循环更加智能。无论是哪种方式,都要确保您知道要用'3'测试哪些有效数据。
发布于 2013-10-12 18:56:42
你在比较一个字符就像个整数。
试试这个:
while (ch=getchar())!='3')发布于 2013-10-12 19:01:52
您需要跳过前一个scanf中的尾换行符,它被用作下一个getchar的输入。
使用:
int c;
while((c=getchar())!='\n' && c != EOF ); //eats newline came from scanf最后一次scanf呼叫之后
https://stackoverflow.com/questions/19337949
复制相似问题