【问题标题】:I want to have 100 structs in a loop or something like that我想在循环中有 100 个结构或类似的东西
【发布时间】: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&lt;100;i++){... scanf("%29s", p[i].name);...
  • 小心。使用scanf("%s", …) 意味着名称和地址字段不能有任何空格。您可能会更好地使用fgets() 来读取行,并在必要时使用sscanf() 来分析它们。注意换行符。此外,您应该通过测试返回值来检查scanf() 函数调用是否成功。如果不是 1,则出现问题。是的;你必须每次检查。干得好,不想写出 100 次相同的代码。这在编程中很重要。避免重复。
  • 空格键是否有问题 - 因为代码需要格式化以使其可读

标签: c arrays struct


【解决方案1】:

我希望有 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 检查@987654330 @返回1

while(scanf(" %29s", string_name) != 1) {
    printf("wrong input");
}

这里,%29s 是为了避免覆盖终止空字符的空格,即字符串末尾的'\0'。在scanf() 成功扫描字符串之前,上述while 循环将不允许程序继续运行。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    相关资源
    最近更新 更多