首页 > 解决方案 > 打印二维字符串数组的函数

问题描述

我是 C++ 的初学者

我一直在尝试制作一个打印出二维数组中所有元素的函数,但我无法完成这项工作,我需要一些帮助。

在我看来,我的 printArray 函数不能将二维数组作为有效的输入数据。谁能给我一个建议?此外,是否有更好的方法来构建多维字符串数组而不使用 std::string?

谢谢你的帮助!

int main ()
{
    
    std::string faces[5] = { "Pig", "sex", "John", "Marie", "Errol"};
    printArray(faces);

    std::string TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    //print2DArray(TwoD);
    
    std::cin.get();
    
}

void print2DArray(std::string x[])
{
    
    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
                    std::cout << x[i][j] << std::endl;
        
        }
    
}

标签: c++arrays

解决方案


您必须为函数参数使用正确的类型(与要传递的数据匹配)。

您还必须在使用它们之前声明或定义函数。

#include <iostream>
#include <string>

void print2DArray(std::string x[][2]); // declare function

int main ()
{
    std::string TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    print2DArray(TwoD);
}

void print2DArray(std::string x[][2])
{

    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
            std::cout << x[i][j] << std::endl;
        
        }

}

如果您不打算修改字符串,使用const char*可能是构建多维字符串数组而不使用的好方法。std::string

#include <iostream>

void print2DArray(const char* x[][2]); // declare function

int main ()
{
    const char* TwoD[2][2] = {{ "Aces", "Deuces"}, { "Hearts", "Diamonds"}};

    print2DArray(TwoD);
}

void print2DArray(const char* x[][2])
{

    for(int i = 0; i < 2; i++)  
        for(int j = 0; j < 2; j++)
        {
            std::cout << x[i][j] << std::endl;
        
        }

}

推荐阅读