【发布时间】:2017-01-03 14:10:49
【问题描述】:
在这个程序中:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct person{
char name[30];
char address[30];
int phoneNumber[30];
char creditRating[30];
};
int main(){
struct person p;
printf("What is the person's name?\n");
scanf(" %s", p.name);
printf("What is the person's address?\n");
scanf(" %s", p.address);
printf("What is the person's phone number?\n");
scanf("%d", &p.phoneNumber);
printf("What is the person's credit rating?\n");
scanf(" %s", p.creditRating);
printf("The person's name is %s\n", p.name);
printf("The person's address is %s\n", p.address);
printf("The person's phone number is %d\n", p.phoneNumber);
printf("The person's credit rating is %s\n", p.creditRating);
return 0;
}
我可以有类似的东西
For(i=0;i>=n;i++)
struct person [i];
printf("What is the person's name?\n");
scanf(" %s", [i].name);
printf("What is the person's address?\n");
scanf(" %s", [i].address);
printf("What is the person's phone number?\n");
scanf("%d", &[i].phoneNumber);
printf("What is the person's credit rating?\n");
scanf(" %s", [i].creditRating);
我希望有 100 个结构及其输入。像这样一一写出来有点难:
struct person p;
.....
struct person q;
.....
//and etc...
我怎样才能避免这种情况?
【问题讨论】:
-
struct person p[100]; for(i=0;i<100;i++){... scanf("%29s", p[i].name);... -
小心。使用
scanf("%s", …)意味着名称和地址字段不能有任何空格。您可能会更好地使用fgets()来读取行,并在必要时使用sscanf()来分析它们。注意换行符。此外,您应该通过测试返回值来检查scanf()函数调用是否成功。如果不是 1,则出现问题。是的;你必须每次检查。干得好,不想写出 100 次相同的代码。这在编程中很重要。避免重复。 -
空格键是否有问题 - 因为代码需要格式化以使其可读