我写了这个C程序,输入3人的名字和年龄。但是输出不是我的期望。它可以输入第一人称的姓名和年龄,但不能输入第二人称和第三人称。请帮忙。
#include <stdio.h>
#include <string.h>
int main()
{
int i, age;
char name[20];
for(i=0; i<3; i++)
{
printf("\nEnter name: ");
gets(name);
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
}
return 0;
}
答案 0 :(得分:1)
简而言之:您的第二个puts
正在处理您的'\n'
中的scanf
。
通过在getchar();
之后添加scanf
来解决
说明:
第一次迭代:
printf("\nEnter name: ");
gets(name); // line is read from input
printf("Enter age: ");
scanf(" %d", &age); // a number is read from input, and the newline char ('\n') remains in buffer
puts(name);
printf(" %d", age);
第二次迭代:
printf("\nEnter name: ");
gets(name); // previously buffered newline char is read, thus "skipping" user input
printf("Enter age: ");
scanf(" %d", &age);
puts(name);
printf(" %d", age);
第3次迭代相同,这就是为什么您失去用户输入的原因
答案 1 :(得分:0)
存储多人信息的最好方法是使用struct,例如
struct person {
int age;
char name[20];
};
并构造一个结构数组,例如
struct person people[3];
与访问people[i].age
和people[i].name
的循环相比,例如,
#include <stdio.h>
#include <string.h>
struct person {
int age;
char name[20];
};
#define ARR_SIZE 3
int main(int argc, char* argv[])
{
struct person people[ARR_SIZE];
int i;
char *lastpos;
for(i = 0; i < ARR_SIZE; i++)
{
printf("\nEnter name: ");
scanf(" %s", people[i].name);
if ((lastpos=strchr(people[i].name, '\n')) != NULL) *lastpos = '\0'; // remove newline from the end
printf("Enter age: ");
scanf(" %d", &people[i].age);
}
printf("This is the people you entered:\n");
for(i = 0; i < ARR_SIZE; i++)
{
printf("%d : %s : %d\n", i+1, people[i].name, people[i].age);
}
return 0;
}
更新:
如您所见,我使用scanf(" %s", people[i].name);
而不是gets(people[i].name);
从name
读取stdin
。在以下情况下,请尝试两种选择:
然后阅读有关scanf
和cleaning input buffer返回的价值的文章