在这个程序中:
<BeaconView dispatch={dispatch.bind(null, store)} />
我可以拥有像
这样的东西吗?#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;
}
我想要输入100个结构。要逐一编写它们有点难:
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);
我该如何避免?
答案 0 :(得分:3)
我希望他们的输入有100个结构,但是很难一个一个地编写它们......
只需使用所需大小的结构数组并循环遍历每个元素。像这样:
struct person p[100]; //array of structures of required size
//loop over each array element
for(int i = 0; i < 100; i++) {
printf("What is the person's name?\n");
scanf(" %s", p[i].name);
printf("What is the person's address?\n");
scanf(" %s", p[i].address);
printf("What is the person's phone number?\n");
scanf("%d", &p[i].phoneNumber);
//NOTE: you are not scanning phone number correctly.
//try using a loop or make it a string.
printf("What is the person's credit rating?\n");
scanf(" %s", p[i].creditRating);
}
此外,正如其他人所建议的那样,避免使用scanf()
会更好。这是why not use scanf()
?的链接。但是,如果你仍然想使用scanf()
,那么检查它的返回值会很好。 scanf()
的返回值是读取的项目数,因为您在每个scanf()
中读取一个字符串( phoneNumber
除外)检查scanf()
是否返回1
while(scanf(" %29s", string_name) != 1) {
printf("wrong input");
}
这里,%29s
是为了避免覆盖终止空字符的空间,即字符串末尾的'\0'
。在while
成功扫描字符串之前,上述scanf()
循环不允许程序继续。
正如@IngoLeonhardt在评论中提到的那样,如果你使用字符串来接收电话号码而不是整数数组,这需要一个循环来放置在连续索引中读取的元素,那么它会更容易。 / p>