c++ - 打印二维字符串数组的函数
问题描述
我是 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;
}
}
解决方案
您必须为函数参数使用正确的类型(与要传递的数据匹配)。
您还必须在使用它们之前声明或定义函数。
#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;
}
}
推荐阅读
- looker - 如何获得维度的总和?
- html - 如何在 node.js 中使用用户输入进行删除或放置请求?
- c# - .NET Core Web 部署到生产时会在发布时关闭站点?
- php - sqlsrv_query 执行不返回结果,但在 sql manager 中执行代码时结果存在
- jquery - 有没有更好的方法来使用 jquery 将组中的最后一个单选按钮设置为“已选中”?
- sql - Derby 数据库错误未写入数据库
- javascript - 尝试使用国际电话输入库作为国家代码时出错
- node.js - 将卷添加到运行命令时忽略 docker 端口映射
- reactjs - 在 React 中,您如何正确地以编程方式导航到新的路由/页面?
- python - 在 Keras 中检测字母是否等于“X”