【发布时间】:2020-01-25 22:51:34
【问题描述】:
我一直在为我的计算机科学课做一个项目,但遇到了代码工作的问题。我没有显示任何错误,除非我尝试编译并收到错误消息:
抛出异常:写访问冲突。 _左边是 0xCCCCCCCC。
我的项目的目的是从外部文件中获取名称列表,将它们读入数组,对所述数组进行排序,然后在使用代码类的同时输出排序后的列表。 这是我的代码的副本,我想感谢任何可以帮助我解决我的问题的人:
**Header File**
#include <iostream>
using namespace std;
class person
{
public:
person();
bool get(ifstream&);
void put(ofstream&);
private:
int capacity = 0;
string first_name[CAPACITY];
string last_name[CAPACITY];
int age[CAPACITY];
};```
**Header function definitions cpp file**
#include<iostream>
#include<string>
#include<fstream>
#include<cstdlib>
const int CAPACITY=20;
using namespace std;
#include "Person.h"
//Names constructor
//Postcondition both first name and last name initialized to zero
person::person()
{
first_name[CAPACITY] = "";
last_name[CAPACITY] = "";
age[CAPACITY]=0;
}
bool person::get(ifstream& in)
{
in >> first_name[CAPACITY] >> last_name[CAPACITY] >> age[CAPACITY];
return(in.good());
}
void person::put(ofstream &out)
{
out << first_name[CAPACITY] << last_name[CAPACITY] << age[CAPACITY];
}
**cpp file which holds main**
#include<iostream>
#include<cstdlib>
#include<fstream>
#include<string>
const int CAPACITY = 20;
using namespace std;
#include "Person.h"
void pop(string *xp, string *yp);
void sort(string name[CAPACITY], int count);
int main()
{
class person names[CAPACITY];
ifstream infile;
ofstream outfile;
string filename;
string name[CAPACITY];
int n = 0;
cout << "Enter the file name you wish to open" << endl;
cin >> filename;
infile.open(filename + ".txt");
outfile.open("Person_New.txt");
if (infile.fail())
{
cout << "The file requested did not open" << endl;
exit(1);
}
while (!infile.eof())
{
names[n].get(infile);
n++;
}
sort(name, CAPACITY);
for (int i = 0; i < CAPACITY; i++)
{
names[i].put(outfile);
}
cout << "The file has been created" << endl;
infile.close();
}
void pop(string *xp, string *yp)
{
string temp = *xp;
*xp = *yp;
*yp = temp;
}
void sort(string name[CAPACITY], int count)
{
int i, j;
for (i = 0; i < count - 1; i++)
{
for (j = 0; j < count - i - 1; j++)
{
if (name[j] > name[j + 1])
{
pop(&name[j], &name[j + 1]);
}
}
}
}
Once again Thank you for any support
【问题讨论】:
-
person类中不需要 any 数组。而且您使用它们不正确 -[CAPACITY]在声明 数组和使用 数组时意味着不同。main中的name数组永远不会用任何有用的东西初始化 - 你所拥有的只是空字符串。请注意,它与您的names数组完全无关。还有Why is iostream::eof inside a loop condition (i.e.while (!stream.eof())) considered wrong? -
我不认为你应该这样使用字符串
-
我建议放弃您目前用于学习 C++ 的资源,转而使用 a good book。 C++ 不是一门简单的语言,正确使用它更难。
-
在许多其他事情中,像`first_name[CAPACITY] = "";`这样的语句写在数组的末尾。在您的情况下,有效的数组索引是
0...CAPACITY-1。 -
不要使用数组,而是使用
std::vector。