简体   繁体   中英

(C++) How do you Display a 2D Array with both Char and Int Values?

#include<iostream>
using namespace std;

int main()

{

string display[2][3] = {{"Name","Geometry","English"},{"Larry",90,85}}; //problem is here
    
    for(int row=0;row<2;row++){
        for(int col=0;col<3;col++){
            cout<<display[row][col]<<" "; 
        }
        cout<<endl;
    }
}

//[Error] invalid conversion from 'int' to 'const char*' [-fpermissive]

You can only have array of only one type. In your case array of strings. So if you want to put your integers into this array you can use:

std::to_string(some_int);

so it will be:

string display[2][3] = {{"Name","Geometry","English"},{"Larry",std::to_string(90),std::to_string(85)}}; //problem is here

I take a guess here, but I have a feeling you took a wrong tool for the job.

It seems that you want structure like CSV file, with first row as header and remaining rows as data. This cannot be done using arrays, because arrays must be homogeneous. You cannot store multiple types in there.
You can of course convert int to a std::string , see the other answer for that, but if the next step will be eg finding mean of the scores, it suddenly becomes much more difficult.

The better solution to store multiple types of data would be to create a class.

#include <iostream>
#include <string>

struct Student
{
    std::string name;
    int geometryScore;
    int englishScore;
};

int main()
{
    Student students[1] {{"Larry",90,85}};
    std::cout << "Name Geometry English\n";
    for(int i = 0; i < 1; i++)
    {
        std::cout << students[i].name << " " << students[i].geometryScore << " " 
                  << students[i].englishScore << "\n";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM