Error] cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string<char>}' through '...'

StackOverflow https://stackoverflow.com/questions/23450300

  •  14-07-2023
  •  | 
  •  

Question

#include <stdio.h>
#include <string>
main()
{
int br_el[6],i;
std::string qr_naziv[6];

    qr_naziv[0]="Bath tub";

    qr_naziv[1]="Sink";

    qr_naziv[2]="Washing machine";

    qr_naziv[3]="Toilet";

    qr_naziv[4]="Kitchen sink";

    qr_naziv[5]="Dish washer";


for(i=0;i<6;i++)
    {

        printf("Input the number for %s =",qr_naziv[i]);\\here lies the problem

scanf("%d",&br_el[i]);
}

This program is much longer, so I shortened it.. The thing is, I will enter numbers for array br_el[6], and I want it to show me for what object I am entering the number! So when I try to compile it gives me the error:"[Error] cannot pass objects of non-trivially-copyable type 'std::string {aka class std::basic_string}' through '...'" I tried to declare string qr_naziv[6]; but the string didn't even bold so it didn't work, so I googled and found out another way (std::string qr_naziv[6];).

Was it helpful?

Solution

Well, C functions are not acquainted with C++ structures. You should do the following:

...
for(i = 0; i < 6; i++) {
    printf("Input the number for %s =", qr_naziv[i].c_str());
    scanf("%d", &br_el[i]);
}
...

Notice the call to the method c_str() on the each std::string qr_naziv[i], which returns a const char * to a null-terminated character array with data equivalent to those stored in the string -- a C-like string.

Edit: And, of course, since you're working with C++, the most appropriate to do is to use the stream operators insertion << and extraction >>, as duly noted by @MatsPetersson. In your case, you could do the following modification:

# include <iostream>
...
for(i = 0; i < 6; i++) {
    std::cout << "Input the number for " << qr_naziv[i] << " =";
    std::cin >> br_el[i];
}
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top