简体   繁体   English

C-扫描字符串并将其分配给结构中的char *吗?

[英]C- Scanning a string and assigning it to a char* within a struct?

I was requested to program a sort of online market that allows you to buy cameras and accesories. 我被要求对某种在线市场进行编程,使您可以购买相机和配件。 I have a struct "User" which i will list bellow. 我有一个结构“用户”,我将在下面列出。 I want to be able to create a user through commandprompt, so in main there is a menu that requests you data (name, locality, country, etc) to registrer the user. 我希望能够通过命令提示符来创建用户,因此在主菜单中有一个菜单可以请求您提供数据(名称,位置,国家/地区等)以注册该用户。 Everything seems quite alright until i try to assign the char* name variable within the struct a value through scanner. 在我尝试通过扫描器为结构中的char * name变量分配值之前,一切似乎都还不错。 (I previuosly initialized the struct, (name == NULL)) (我预先初始化了该结构,(名称== NULL))

    switch (option) {
        case 1:
            printf("New User Registration:\n");
            user = newUser();
            while (user->name == NULL) {
                printf("Insert users name:\n");
                scanf("%s",user->name);
                printf("%s",user->name);
            }

Also heres the function newUser(). 还继承了函数newUser()。 Please be very detailed in your answers, im very new to C and its quite dificult for me. 请在您的答案中非常详细地介绍一下,这对C来说还很陌生,对我而言却很难。

User* newUser(){
User* user = (User*)malloc(sizeof(User));
if(user != NULL){
    user->name= NULL;
    user->country= NULL;
    user->direction=NULL;
    user->id=NULL;
    user->locality=NULL;
    user->phoneNumber=NULL;
    user->postalCode=NULL;
    user->province=NULL;
    user->role = client;
}
return user;

} }

You probably want the m option. 您可能需要m选项。 Change your scanf call to 将您的scanf呼叫更改为

scanf("%ms", &user->name);

scanf man page scanf手册页

An optional 'm' character. 可选的“ m”字符。 This is used with string conversions (%s, %c,%[), and relieves the caller of the need to allocate a corresponding buffer to hold the input: instead, scanf() allocates a buffer of sufficient size, and assigns the address of this buffer to the corresponding pointerargument, which should be a pointer to a char * variable (this variable does not need to be initialized before the call). 它与字符串转换(%s,%c,%[)一起使用,使调用者无需分配相应的缓冲区来保存输入:相反,scanf()分配了足够大小的缓冲区,并分配了地址此缓冲区的值到对应的指针参数,该指针参数应该是指向char *变量的指针(在调用之前不需要初始化此变量)。 The caller should subsequentlyfree(3) this buffer when it is no longer required. 当不再需要此缓冲区时,调用者应随后释放(3)此缓冲区。

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

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