访问违规写入定位
Access violation writing locating
我无法弄清楚我的代码有什么问题。我使用 add watches 来确保信息被正确读取并输入到数组中。我得到的错误是:
Access violation writing location.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
//string name;
//double id = 0;
int numQ = 0;
int numA = 0;
string temp;
string arrayQ[50];
string arrayA[50];
fstream SaveFile;
SaveFile.open("TestBank.txt", ios::in);
while (!SaveFile.eof())
{
getline(SaveFile, temp, '#');
if (temp.length() > 5)
{
arrayQ[numQ] = temp;
numQ++;
}
else
{
arrayA[numA] = temp;
numA++;
}
}
SaveFile.close();
cout << "The question is\n" << arrayQ[0] << endl;
cout << "The answer is\n" << arrayA[0] << endl;
return 0;
}
首先你不应该在 C++ 中循环 eof。
那么你应该确保numQ
和numA
不会越界,因为它们的值取决于文件内容:
...
while (getline(SaveFile, temp, '#'))
{
if (temp.length() > 5)
{
if (numQ>=50)
cerr << "Ouch ! numQ=" <<numQ<<endl;
else arrayQ[numQ] = temp;
numQ++;
}
else
{
if (numA>=50)
cerr << "Ouch ! numA=" <<numA<<endl;
else arrayA[numA] = temp;
numA++;
}
}
最后,您可以考虑使用 vector<string>
而不是字符串数组。在这种情况下,您只需 push_back()
正确向量中的字符串,而不必担心预定大小。
我无法弄清楚我的代码有什么问题。我使用 add watches 来确保信息被正确读取并输入到数组中。我得到的错误是:
Access violation writing location.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
//string name;
//double id = 0;
int numQ = 0;
int numA = 0;
string temp;
string arrayQ[50];
string arrayA[50];
fstream SaveFile;
SaveFile.open("TestBank.txt", ios::in);
while (!SaveFile.eof())
{
getline(SaveFile, temp, '#');
if (temp.length() > 5)
{
arrayQ[numQ] = temp;
numQ++;
}
else
{
arrayA[numA] = temp;
numA++;
}
}
SaveFile.close();
cout << "The question is\n" << arrayQ[0] << endl;
cout << "The answer is\n" << arrayA[0] << endl;
return 0;
}
首先你不应该在 C++ 中循环 eof。
那么你应该确保numQ
和numA
不会越界,因为它们的值取决于文件内容:
...
while (getline(SaveFile, temp, '#'))
{
if (temp.length() > 5)
{
if (numQ>=50)
cerr << "Ouch ! numQ=" <<numQ<<endl;
else arrayQ[numQ] = temp;
numQ++;
}
else
{
if (numA>=50)
cerr << "Ouch ! numA=" <<numA<<endl;
else arrayA[numA] = temp;
numA++;
}
}
最后,您可以考虑使用 vector<string>
而不是字符串数组。在这种情况下,您只需 push_back()
正确向量中的字符串,而不必担心预定大小。