Dancia
Dancia

Reputation: 812

Value of type char* cannot be used to initialize an entity of type “char”

Tab seperated example.txt file:

1    MODEL1
2    MODEL2
3    MODEL3

My main:

int main()
{
    int number;
    char model[6];
    list myList;

    ifstream infile;
    infile.open("example.txt");

    //reading first line from file
    infile >> (int)number;
    infile >> model;
    myList.Insert({ number, model}, 1); // error here on model

    return 0;
}

Pseudo of myList class:

struct data{
    int number;
    char model[6];
};

struct Node{
    data data;
    ...
};

Node = myNode[100]

void Insert(data x, int position)
{
    myNode[position].data = x;
}

I have problems reading my second row of chars from example.txt file. How do I read MODEL1, MODEL2, MODEL3 into myList?

Upvotes: 1

Views: 3036

Answers (1)

flogram_dev
flogram_dev

Reputation: 42888

{number, model} is trying to initialize the member variable model as a copy of the local model, but raw arrays can't be copy-initialized.

You'll have to use std::string:

int main()
{
    int number;
    std::string model;
    list myList;

    ifstream infile;
    infile.open("example.txt");

    infile >> number;
    infile >> model;
    myList.Insert({number, model}, 1);
}

and

struct data
{
    int number;
    std::string model;
};

This will also fix the buffer overflow bug that @user2079303 and @JoachimPileborg spotted.


You can also keep the raw array, and manually strncpy the local model array to the member model. However this is not advised in C++.

Upvotes: 1

Related Questions