2017-01-03 37 views
1

在这个程序中的东西100层结构:我想有一个循环或类似的

#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... 

我该如何避免这种情况?

+2

'struct person p [100];对于(i = 0; i <100; i ++){... scanf(“%29s”,p [i] .name); ...' – BLUEPIXY

+2

要小心。使用'scanf(“%s”,...)'表示名称和地址字段不能带空格。你可能会用'fgets()'来读取行和'sscanf()',以便在必要时分析它们。谨防换行符。此外,你应该通过测试返回值来检查'scanf()'函数调用是否成功。如果不是1,则出现问题。是;你必须每次检查。干得不错,因为不想将相同的代码写出100次。这在编程中很重要。避免重复。 –

+2

空格键是否存在问题 - 因为代码需要格式化以使其可读 –

回答

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是为了避免覆盖读取一个字符串空格为,终止空字符即位于字符串末尾。上述while循环将不允许程序继续执行,直到scanf()成功扫描字符串为止。

@IngoLeonhardt在评论中提到,如果您使用字符串接收电话号码而不是整数数组,它需要一个循环来将元素读入连续索引中。

相关问题