【问题标题】:How do I add a string to a struct using a function?如何使用函数将字符串添加到结构中?
【发布时间】:2020-07-26 11:16:27
【问题描述】:

我做了一个停车系统,我使用 void 功能输入车辆的信息。 但我不知道如何使用 void 将字符串放入结构中。

这是我的代码。 我的错在哪里?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct car {
  char plate[10];
  char model[20];
  char color[10];
};

void main() {

  struct car c[4];

  AddCar(c[0], "43ds43", "ford", "blue");
  ShowCar(c[0]);

  return 0;
}
// I guess my mistake is here
void AddCar(struct car c, char p[10], char m[10], char r[10]) {
  strcpy(c.plate, p);
  strcpy(c.model, m);
  strcpy(c.color, r);
}

void ShowCar(struct car c) {
  printf("Plate: %s   Model: %s  Color: %s\n-------", c.plate, c.model, c.color);
}

【问题讨论】:

    标签: c string struct char void


    【解决方案1】:

    您的代码中有许多错误!首先解决“其他”问题:

    1. 您需要在使用之前为AddCarShowCar 提供函数原型,否则编译器会假定它们返回int,然后在看到实际值时抱怨 定义。
    2. 您的main 函数(正确)返回0,但它被声明为void - 所以将其更改为int main(...)

    还有“真正的”问题:您将car 结构传递给AddCar 按值 - 这意味着制作了一个副本,然后将其传递给函数。对该副本的更改不会影响调用模块中的变量(即main)。要解决此问题,您需要将 指针 传递给 car 结构,并在该函数中使用 -&gt; 运算符(代替 . 运算符)。

    这是您的代码的“固定”版本,在我进行重大更改的地方添加了 cmets:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    struct car {
        char plate[10];
        char model[20];
        char color[10];
    };
    
    // Add your functions' prototypes before you use them...
    void AddCar(struct car *c, char p[10], char m[10], char r[10]);
    void ShowCar(struct car c);
    
    int main() // If you return an int, you must declare that you do!
    {
        struct car c[4];
        // Here, we pass a pointer to `c[0]` by adding the `&` (address of)...
        AddCar(&c[0], "43ds43", "ford", "blue");
        ShowCar(c[0]);
        return 0;
    }
    
    void AddCar(struct car *c, char p[10], char m[10], char r[10])
    {                   // ^ To modify a variable, the function needs a POINTER to it!
        strcpy(c->plate, p);
        strcpy(c->model, m);  // For pointers to structures, we can use "->" in place of "."
        strcpy(c->color, r);
    }
    
    void ShowCar(struct car c)
    {
        printf("Plate: %s   Model: %s  Color: %s\n-------", c.plate, c.model, c.color);
    }
    

    请随时要求进一步澄清和/或解释。

    【讨论】:

    • 另外,如果我想在struct里面加上时间,应该怎么写成void呢?谢谢评论
    • @MLHYLMZ 您的时间字段将采用什么格式/类型?整数(分钟数或秒数)还是其他?
    • 我想在字符串或整数中添加当前时间没关系。当我说ShowCar时,我希望它单独写入当前时间。示例:板:12gds43型号:丰田颜色:黑色添加时间: 22:32
    • This answer 可以帮助您将时间作为字符串。
    • ...您可以将time_t 成员添加到您的car 结构中,在AddCar 中设置该值,然后按照ShowCar 函数中该答案中的描述对其进行格式化。
    【解决方案2】:

    您正在复制struct car c。将其作为指针传递:

     AddCar(&c[0], "43ds43", "ford", "blue");
     // ...
     void AddCar(struct car *c,char p[10],char m[10],char r[10]) {
        strcpy(c->plate,p);
        strcpy(c->model,m);
        strcpy(c->color,r);
     }
    

    【讨论】:

      猜你喜欢
      • 2019-08-26
      • 2021-11-15
      • 1970-01-01
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多