简体   繁体   中英

Assigning values to chars in structs - c

I have been having trouble getting my head around allowing a user to enter words into structs. The struct I am using is below

struct class
{
  char class_num[4];
  char *class_name;
}

If anyone could point me how to do this or at least point me in the right direction that wuld be great. thanks

What is "class_num" supposed to be?

In general, you have to manage string memory explicitly. The function strdup() might help. Consider:

struct class cls;
char buf[256] = {0};
puts("Name?");
fgets(buf, 255, stdin);
cls.class_name = strdup(buf); 
//you need to free "cls.class_name" after its use is over

This will let the user enter a string up to 255 characters, and will store (a copy of) that string in the "class_name" member of the struct instance "cls".

In C chars are just a type of integer, except that they can be signed or unsigned (int is signed by default). So class_num[i] is a one byte integer. There are many ways to do input, and it depends on whether it's supposed to be a string or a four byte code or whatever. As Jon watt said, you'll also have to manage memory for the other field. You might look up scanf or strtod or strtol combined with read or fread. Unless you have a more sophisticated input in place like a database.

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.

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