简体   繁体   English

使用 C 语言创建具有给定字符串的结构名称

[英]Create a struct name with a given string in C language

I want to create a code that does something like this:我想创建一个执行以下操作的代码:

typedef struct {
  char name[1024];
  int age;
  char gender;
}person;

person Jacob = {.name = "Jacob", .age = 15, .gender = 'M'};

But I need to use the scanf option to get the variables, something like this:但我需要使用 scanf 选项来获取变量,如下所示:

typedef struct {
   char name[1024];
   int age;
   char gender;
}person;

char name_person[1024];
int age_person;
char gender_person;
scanf(" [:^\n],%d,%c",name_person,&age_person,&gender_person);

I would know if I can do something like this:我会知道我是否可以做这样的事情:

person name_person = {.name = name_person, .age = age_person, .gender = gender_person};

To do the same thing as the code above?做和上面的代码一样的事情? I'm sorry if it sounds like a stupid question, I'm very new to C language.如果这听起来像一个愚蠢的问题,我很抱歉,我对 C 语言很陌生。

For name you need to use c builtin func to make copies... the other field of your struct can be assigned straightforward对于名称,您需要使用 c 内置函数进行复制...您的结构的其他字段可以直接分配

You can use scanf with struct like this.您可以像这样将 scanf 与 struct 一起使用。

typedef struct {
   char name[1024];
   int age;
   int sex;
}person;

person human;
scanf(" [:^\n],%d,%c",human.name,&human.age,&human.sex);

or you can use struct like this或者你可以使用这样的结构

person human;
char c;
int a;
float b;

scanf("%c %d %f",&c,&a,&b);

human.name=c;
human.age=a;
human.sex=b;

When using 'scanf' you need to match the format to the variable.使用“scanf”时,您需要将格式与变量匹配。

The scanf will deal with the name (char []), and age (int), but you will temporary variable to handle the conversion of the 'sex' attribute from char to int. scanf将处理名称 (char []) 和年龄 (int),但您将使用临时变量来处理 'sex' 属性从 char 到 int 的转换。

Also consider change to format - looks like the input is comma separated.还要考虑更改格式 - 看起来输入是逗号分隔的。 If this is the case then'%[^,]' will work.如果是这种情况,那么 '%[^,]' 将起作用。

{
        // Good idea to initialize 'p'.
        person p = {} ;
        char sex ;

        scanf(" %[^,],%d,%c", p.name, &p.age, &sex) ;
        p.sex = sex ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM