-2 c++ exception indexoutofboundsexception
在该程序中,用户在命令行中输入两个字符串.其中一个是数字,另一个是字符串.该程序用于根据电话拨号盘上每个按钮上的数字/字母检查输入的数字和字符串是否相同.我得到一个例外,说:
Run Code Online (Sandbox Code Playgroud)Unhandled exception at 0x775DDAE8 in Project10.exe: Microsoft C++ exception: std::out_of_range at memory location 0x0018F158.
非常感谢任何帮助,非常感谢你:)
using namespace std;
bool checkPswd(string keyStrokes, string password) {
string temp;
string temp2;
bool temporary = 1;
string phoneButtons[10] = {
"", ""
"abc", "def", "ghi", "jkl",
"mno", "pqrs", "tuv", "wxyz"
};
for (int i = 0; i < keyStrokes.length(); i++) {
for (int j = 2; j < 10; j++) {
for (int k = 0; k < phoneButtons[j].length(); k++) {
temp = phoneButtons[j];
if (password.at(k) == temp.at(k)) {
temp2 = +(char)k;
}
else {
//do nothing
}
}
}
}
cout << temp2;
for (int m = 0; m < temp2.length(); m++) {
if (temp2.at(m) == keyStrokes.at(m)) {
//keep searching
}
else {
return 0;
}
}
return 1;
}
int main(int argc, char ** argv) {
if (argc != 3) {
cout << "Please input the key strokes from the phone and the password." << endl;
return 1;
}
string keyStrokes = argv[1];
string password = argv[2];
bool check;
check = checkPswd(keyStrokes, password);
if (check) {
cout << "Password Verified" << endl;
}
else {
cout << "Wrong Password" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
for (int k = 0; k < phoneButtons[j].length(); k++) {
Run Code Online (Sandbox Code Playgroud)
k将在这里迭代,从0到1小于`phoneButtons [j]中的字符数
if (password.at(k) // ... rest of the code is irrelevant
Run Code Online (Sandbox Code Playgroud)
流行测验:如果password字符少于phoneButtons[j],你认为这会发生什么?
for (int m = 0; m < temp2.length(); m++) {
if (temp2.at(m) == keyStrokes.at(m)) {
Run Code Online (Sandbox Code Playgroud)
同样的错误也在这里.我还没有分析所显示代码的其余部分,以了解同一逻辑错误的任何其他情况.
这就是你应该使用的原因#include <algorithm>,而不是使用这些容易出错的C风格for循环.std::find()比这种基于C风格的循环搜索更不容易出错.
| 归档时间: |
|
| 查看次数: |
1679 次 |
| 最近记录: |