0
How to assign an integer to a struct array? C++
Here is the main idea, I have a struct array, where I want to insert some elements (name and code), but when I try to assign an integer to struct array, gives me an error: Error: no match operator (operand types are 'Products' and 'int') How can I solve this error? I have no idea about how to do this... https://code.sololearn.com/c6UG07M5s8Je/?ref=app
9 Réponses
+ 4
The user inputs the integer, what about the name of the product? Is it deduced from the integer? What should be the name of the product if it isn't obtained from the user? You are supposed to create the product before placing it into the product array.
+ 4
So assuming you have your struct
struct Products{
std::string name;
int code;
};
and the user inputs to temporary variables like:
int c; std::string n;
cin >> c >> n;
you can build a temporary struct instance before passing it as _element into the function you wrote:
Products temp;
temp.name = n;
temp.code = c;
insertDate(yourDate, temp);
+ 2
The error is actually on line 17
product[_position + i] = _element;
You are trying to assign an integer to an array which holds structs of type Products. You actually want to assign that integer to the integer member "code" within the struct.
product[_position + i].code = _element;
+ 2
Eduardo Perez Regin By printing the struct, you want to print the value of the struct members, so:
cout << product[0].name << " " << product[0].code;
will show you what is stored in product[0]. You can't print the struct element directly, since the program doesn't know what to output.
+ 1
Then you shouldn't be passing _element as an int, and instead pass it as a Products.
void insertDate(int _position, Products _element)
+ 1
Ok, you are right about your last comment, I was trying to do is, the user puts the position and in the second parameter the name of the product, but... dunno how to do it if it recieve a struct
+ 1
I see... But how can I print the product array? If I try to print, using this:
Cout<<product [0];
Give me an error, "no match for operator <<", I try to see if the element was inserted using this cout, but dunno how to solve this...
0
But I want to change the whole array, not only code, if the user choose insert, I want to insert a new product, not to the I refer member "code"
0
But how can I put the element? If the user will enter an integer and not a Product? I need an integer because that will be the value that will replace the previous value on the array