c++ - 与二维数组有关的循环崩溃程序

标签 c++ arrays loops crash

我正在创建一个编码程序,当我指示该程序基于字母表创建一个 5X5 网格时,同时跳过与某些预定义变量匹配的字母(这些变量在运行时由用户输入给定值)。我有一个循环指示循环继续运行,直到访问数组的值超出范围,循环似乎导致了问题。这段代码是标准化的,所以在另一个编译器中编译它应该不会有太大问题。将我的程序分成函数也会更好吗?这是代码:

#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<limits>

using namespace std;
int main(){


 while (!cin.fail()) {      

char type[81];
char filename[20];
char key [5];
char f[2] = "q";
char g[2] = "q";
char h[2] = "q";
char i[2] = "q";
char j[2] = "q";
char k[2] = "q";
char l[2] = "q";
int a = 1;
int b = 1;
int c = 1;
int d = 1;
int e = 1;
string cipherarraytemplate[5][5]= {
{"a","b","c","d","e"},
{"f","g","h","i","j"},
{"k","l","m","n","o"},
{"p","r","s","t","u"},
{"v","w","x","y","z"}

};
string cipherarray[5][5]= {
{"a","b","c","d","e"},
{"f","g","h","i","j"},
{"k","l","m","n","o"},
{"p","r","s","t","u"},
{"v","w","x","y","z"}

};





cout<<"Enter the name of a file you want to create.\n";

cin>>filename;


ofstream outFile;
outFile.open(filename);
outFile<<fixed;
outFile.precision(2);
outFile.setf(ios_base::showpoint);
cin.ignore(std::numeric_limits<int>::max(),'\n');






cout<<"enter your codeword(codeword can have no repeating letters)\n"; 

cin>>key;

while (key[a] != '\0' ){

while(b < 6){
cipherarray[b][c] = key[a];

 if (  f == "q" ) {
 cipherarray[b][c] = f;
}

 if ( f != "q" && g == "q"  )
 {
cipherarray[b][c] = g;
}

 if ( g != "q" && h == "q" )
 {
cipherarray[b][c] = h;
}

 if ( h != "q" && i == "q"  )
 {
cipherarray[b][c] = i;
}


 if ( i != "q" && j == "q" ) 
{
cipherarray[b][c] = j;
}

 if ( j != "q" && k == "q" )
 {
cipherarray[b][c] = k;
}

 if ( k != "q" && l == "q" )
 {
cipherarray[b][c] = l;
}
a++;
b++;

}

c++;
b = 1;

}

while (c < 6 || b < 6){

if (cipherarraytemplate[d][e] == f || cipherarraytemplate[d][e] == g || cipherarraytemplate[d][e] == h || cipherarraytemplate[d][e] == i ||
cipherarraytemplate[d][e] == j || cipherarraytemplate[d][e] == k || cipherarraytemplate[d][e] == l){
 d++;                 
}
else {
cipherarray[b][c] = cipherarraytemplate[d][e];
d++;
b++;
}
if (d == 6){
d = 1;
e++;
}
if (b == 6){
c++;
b = 1;
}

 cout<<"now enter some text."<<endl<<"To end this program press Crtl-Z\n";

while(!cin.fail()){

 cin.getline(type,81);

outFile<<type<<endl;
}

outFile.close();
}
} 

我知道会有一些四十多岁的人偶然发现这篇文章,他已经编程了 20 多年,他会看我的代码并说:“什么是这家伙在干什么”。

最佳答案

密码数组的长度为 [5] 个条目,这意味着它可以用 (0, 1, 2, 3, 4) 中的任何一个进行索引 - 传入 5 是越界的。

修改你的while (b < 6)阅读while (b < 5)保持在数组边界内(在您检查索引的其他地方也类似)。

关于c++ - 与二维数组有关的循环崩溃程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4702825/

相关文章:

c# - 将 int 值转换为 3 字节数组(反之亦然)

c++ - 捕获到缓冲区 QT

javascript - array[1][2] 是什么意思?

c++ - Double.parseDouble() 等同于 C++?

javascript - 从所有数组项中切片字符

ruby - 在 Ruby 中将成对的数组元素混合在一起的最佳方法

JAVA:将替代(||)放入循环中?

java - 需要一双新的眼睛来弄清楚比较 map 中的值背后的逻辑

c++ - 如何加快这个用于选择子矩阵的 GSL 代码?

c++ - 模板参数的缩写(Vector3 而不是 Vector<3>)