我创建了一个char数组,基本上输入行数和列数,并输入每一行和每列的字母,例如x和y。基本上,就像一个普通的数组但是有字母。输入字母并使用数组结束后,我希望输入2个数字,以便在数组中指定特定的char。例如,我的数组是3x3。我用字符x和y填充数组。在我这样做后,我进入2 2。在第2行和第2列,字母是y。所以我想打印出y。
这是我的密码。
#include <iostream>
using namespace std;
int main()
{
int x,y;
cin>>x>>y;
char n[x][y];
for(int i=0;i<x;i++)
{
for(int j=0;j<y;j++)
{
cin>>n[i][j];
}
}
int a,b;
cin>>a>>b;
cout<<n[a][b];
}发布于 2022-05-15 14:30:43
给定程序的主要问题是,在标准C++中,数组的大小必须是编译时间常数。这意味着以下内容无效:
int x,y;
cin>>x>>y;
char n[x][y];//not standard C++ because x and y are not constant expressions要解决这个问题,可以使用std::vector<char>,如下所示:
#include <iostream>
#include<vector>
int main()
{
int x,y;
std::cin>>x>>y;
//create a 2D vector
std::vector<std::vector<char>> n(x, std::vector<char>(y));
//iterate through rows
for(auto& row: n)
{
//iterate through each element in the row
for(auto& col: row)
{
std::cout<<"enter element: "<<std::endl;
std::cin>>col; //take input from user
}
}
int a,b;
std::cout<<"a and b"<<std::endl;
std::cin>>a>>b;
std::cout<<"element at position: "<<a<<" "<<b <<" is: "<<n[a][b];
}https://stackoverflow.com/questions/72248986
复制相似问题