Home > OS >  c initialize char array member of a class with a string
c initialize char array member of a class with a string

Time:12-10

i have a class which has several members of char arrays, and i want to initialize this class with an array of strings which are the values of the char arrays.

class Product {
public:
    char productId[20];
    char productName[50];
    char price[9];
    char stock[9];

    Product(vector<string> v) : productId(v[0]), productName(v[1]), price(v[2]), stock(v[3]) {  }
};

with this code i get an error that say no suitable conversion function from "str::string" to "char[20]" exist

CodePudding user response:

The code at the bottom will work. But is this a good idea? Probably not. You are better of just storing std::string in your Product type directly:

#include <cassert>
#include <iostream>
#include <vector>

#include <string.h>

class Product {
public:
  std::string productId;
  ...

  Product(std::vector<std::string> v) : productId{std::move(v[0])} {}
};

There is a problem with this code though; where do you check the vector has all required elements? Better to make an interface that specifies the four strings a Product is made up of separately:

class Product {
public:
  std::string productId;
  ...

  Product(std::string pid, ...) : productId{std::move(pid)}, ... {}
};

But in case you insist on a C/C amalgamation;

#include <cassert>
#include <vector>

#include <string.h> // strcpy

class Product {
public:
  char productId[20];
  char productName[50];
  char price[9];
  char stock[9];

  Product(const std::vector<std::string> &v) {
    assert(!v.empty()); // really; v.size() == 4
    ::strncpy(productId, v[0].c_str(), 19);
    productId[19] = '\0';
    // ...etc.
  }
};
  •  Tags:  
  • c
  • Related