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:
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.
For name you need to use c builtin func to make copies... the other field of your struct can be assigned straightforward
You can use scanf with struct like this.
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.
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.
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 ;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.