c - 我想在一个循环或类似的东西中有 100 个结构

标签 c arrays struct

在这个程序中:

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

我怎样才能避免这种情况?

最佳答案

I want to have 100 structs with their inputs, but it is so hard to write them one by one...

只需使用所需大小的结构数组,然后循环遍历每个元素。像这样:

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' .在 scanf() 成功扫描字符串之前,上面的 while 循环不允许程序继续。

作为@IngoLeonhardt在评论中已经提到,如果您使用字符串而不是整数数组来获取电话号码会更容易,后者需要一个循环来放置在连续索引中读取的元素。

关于c - 我想在一个循环或类似的东西中有 100 个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445410/

相关文章:

c - Makefile:没有链接问题的编译

c - linux/ext2_fs.h 有什么问题?我已经包含了 <linux/fs.h>

php - 无法在 php 中使用 preg_match 通过特殊符号分割字符串

arrays - json 解码后缺少结构对象的嵌套数组

c - C中包含结构的结构中的字节分配

c++ - 2个类似typedef定义的差异

C Segmentation fault 错误打印

c - c中函数指针的用例

Java 多维 ArrayList Int

C++:很少改变大小的大型动态结构数组,是否需要 Vector?