搜索2D字符串数组并打印嵌套数组

问题描述 投票:0回答:1

我是C / C ++的新手,正在努力寻找2D数组。我想接受用户输入并将其与每个嵌套数组的第3个元素进行比较,如果用户输入与该嵌套数组的第3个元素匹配,则打印整个嵌套数组。目前我只有这个-

using namespace std;

int main()
{

    const char *songs[15][3] = {
        {"Stand by Me","Ben E King","Classical"},
        {"Africa","Toto","Rock"},
        {"War Pigs","Black Sabbath","Rock"},
        {"Mr. Rager","Kid Cudi","Rap"},
        {"Don't Stop Believing","Journey","Rock"},
        {"Have You Ever Seen the Rain","Creedance Clearwater","Classical"},
        {"Juicy","Notorious B.I.G","Rap"},
        {"Hands","Mac Miller","Rap"},
        {"The Box","Roddy Ricch","Rap"},
        {"Tiny Dancer","Elton John","Classical"},
        {"Stairway to Heaven","Led Zeppelin","Rock"},
        {"Californication","Red Hot Chili Peppers","Rock"},
        {"Good Mornin","Kanye West","Rap"},
        {"Everybody","Logic","Rap"},
        {"Last Resort","Papa Roach","Rock"}
    };

}

我想按流派搜索二维数组的“歌曲”,然后返回歌曲和歌手。

c++ arrays search multidimensional-array
1个回答
0
投票
Running sample

//... std::string in; //for user input std::cout << "Enter genre: "; std::cin >> in; //get user input for( int i = 0; i < 15; i++){ if(in == songs[i][2]){ //compare to genre std::cout << songs[i][0] << ", " << songs[i][1] << ", " << songs[i][2]<< std::endl; //print all line } } //...

请注意,应该使用C ++容器而不是C样式的char数组,例如,对于固定大小的数组,请使用std::array;对于可变大小的数组,请使用std::array

© www.soinside.com 2019 - 2024. All rights reserved.