0
我檢查了我所有的字符串和數組。沒有什麼看起來不對我。我的包括陳述可能是問題。也許我錯過了一個。我是一個新手程序員。所以我無能爲力,爲什麼這段代碼不起作用。它看起來是正確的,應該絕對有效。每當我調試此代碼時,我都會收到「下標超出範圍錯誤」。有人能幫我指出錯誤或錯誤嗎?
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<fstream>
#include<string>
using namespace std;
int main()
{
int i;
char response;
char answers[20];
char uresponse[20];
int score=0;
srand(time(0));
int test_num = rand() % 2+1;
// cout << test_num << endl;
if (test_num == 1)
{
string line;
ifstream myfile ("form1.txt");
getline (myfile,line);
// cout<< line<<endl;
for (int i = 0; i <= 19; i++)
{
answers[i] = line[i*2];
// cout<<answers[i]<<endl;
}
getline (myfile,line);
if (myfile.is_open())
{
int x = 0;
while (myfile.good())
{
char answers[20];
string line;
getline (myfile,line);
// cout<< line << endl;
if(line == "")
{
cout << "Enter answer: ";
cin >> response;
if(response == 'a', 'A' || response == 'b', 'B' || response == 'c', 'C' || response == 'd', 'D')
{
response = response;
}
else
{
cout << "ERROR. You must enter A, B, C, or D. Please re-enter: ";
cin >> response;
}
response = toupper(response);
uresponse[x] = response;
x++;
}
}
// cout << uresponse <<endl;
// system("pause");
}
else
{
myfile.close();
}
}
else
{
string line;
ifstream myfile ("form2.txt");
getline (myfile,line);
// cout<< line<<endl;
for (int i = 0; i <= 19; i++)
{
answers[i] = line[i*2];
// cout<<answers[i]<<endl;
}
getline (myfile,line);
if (myfile.is_open())
{
int x = 0;
while (myfile.good())
{
char answers[20];
string line;
getline (myfile,line);
// cout << line << endl;
if(line == "")
{
cout << "Enter answer:";
cin >> response;
if(response == 'a', 'A' || response == 'b', 'B' || response == 'c', 'C' || response == 'd', 'D')
{
response = response;
}
else
{
cout << "ERROR:You must enter A, B, C, or D. Please re-enter:";
cin >> response;
}
response = toupper(response);
uresponse[x] = response;
x++;
}
}
// cout<<uresponse<<endl;
// system("pause");
}
else
{
myfile.close();
}
}
for (int j=0; j<20; j++)
{
if (answers[j] == uresponse[j])
score += 1;
}
if(score >15)
{
cout << "CONGRATULATIONS! You Passed with a score of ";
cout << score << endl;
system("pause");
}
else
{
cout<< "You Failed with a score of ";
cout << score << endl;
system("pause");
}
system("pause");
return 0;
}`enter code here`
我明白這會怎樣造成問題。謝謝。我糾正了這個和其他幾個錯誤(與超出範圍錯誤無關)。但是,每次都是「超出範圍」。此外,我正在使用Visual Studio 2012.我的實驗室合作伙伴使用不同的版本,較早的版本。我們在他的版本中開發了代碼。這可能與它有關嗎? – user1745480
@ user1745480查看我更新的答案。看起來像調試是爲了。我Kindly建議你得到一個調試器,並學習使用它:) –
謝謝。但我警告過你,我是新手。無論如何,如果我在第60行添加了語句'x <127',第108行添加了'x <118'。這些數字相當於我打開的每個文本文件中的行數。 – user1745480