Home > Net >  Can't Print array with multiple data types
Can't Print array with multiple data types

Time:05-06

I created a struct named products that contains multiple data types:

struct products{
    int ID;
    string Name;
    double Price;
    int Quantity;
};

Then in the main function, I created an array named details which utilizes the struct products:

int main(){
    struct products details[5];

Then I gave each array element data.

details[0] = {1, "Apple Juice", 12, 240};
details[1] = {2,"Bread", 10, 100};
details[2] = {3, "Chocolate", 5, 500};
details[3] = {4, "Dates", 50, 150};
details[4] = {5, "Eggs", 30, 360};

finally, I tried to print the values of the element at index 2:

cout<<details[2]; 

it gave me this error:

"Invalid operands to binary expression ('std::ostream' (aka 'basic_ostream') and 'struct products')"

Here is a picture of the whole code

enter image description here

CodePudding user response:

There are several ways of doing what you need, here's 3 of them:

  1. Overload << operator:
std::ostream& operator<< (std::ostream& os, const products& pr)
{
    return os << pr.ID << " " << pr.Name << " " << pr.Price << " " << pr.Quantity;
}

std::cout << details[2]; should now work as expected.


  1. Print the struct members directly:

    std::cout << details[2].ID << " " << details[2].Name 
        << " " << details[2].Price << " " <<  details[2].Quantity;
    

  1. Add a to_string() member function:
struct products{
    
//...

    std::string to_string() const
    {
        std::ostringstream os; // #include <sstream>
        os << ID << " " << Name << " " << Price << " " << Quantity;
        return os.str();
    }
};

Usage:

std::cout << details[2].to_string();

CodePudding user response:

i write you like code.

#include <iostream>
using namespace std;

struct H{
    int n;
    int b;
};

int main() {
    H h[] = {10, 20};
    cout << h[0] << endl; // you can not print it becouse it is array!
    return 0;
}

in this code i try to print struct! but i can not do it!

it like:

#include <iostream>
using namespace std;

struct H{
    int n;
    int b;
};

int main() {
    H h = {10, 20};
    cout << h << endl;
    return 0;
}

just try:

#include <iostream>
using namespace std;

struct H{
    int n;
    int b;
};

int main() {
    H h[] = {10, 20};
    cout << h[0].n << endl;
    cout << h[0].b << endl;
    return 

0; }

  • Related