-1
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include <vector>
using namespace std;
class student
{
public:
string s;
int age;
};
ostream& operator<<(ostream &output,const student &s)
{
output << s.s << " " << s.age << "\n";
return output;
}
istream& operator >>(istream& in, student& val)
{
return in >> val.s >> val.age;
}
bool valuecmp(const student & a, const student & b)
{
return a.s < b.s;
}
int main (void)
{
vector<student> a;
student b;
cin>>b.s;
cin>>b.age;
fstream myfile;
myfile.open("a1.txt",ios::app);
int i = 0;
myfile << b;
cout<<"File has been written"<<"\n";
myfile.open("a1.txt",ios::in);
for (string line; getline(myfile, line);)
{
istringstream stream(line);
student person;
stream >> person;
a.push_back(person);
cout<<a[i].s<<a[i].age<<"\n";
i++;
}
sort(a.begin(),a.end(),valuecmp);
fstream my;
my.open("a2.txt",ios::out);
student c;
for (i = 0; i < 2; i++)
{
cout<<a[i].s<<a[i].age<<"\n";
c = a[i];
my << c;
}
return 0;
}
一个简单的程序来接受用户输入,存储在一个对象中。在运行此程序之前,我已在文件中有多个输入。所以,当我让这个程序接受来自用户的输入时,写入一个文件,然后使用排序操作对整个文件的内容进行排序,然后将排序的输出写入一个新文件。为什么我在此看到seg故障?
这接受用户输入,显示消息,File has been written
,但随后显示seg故障。为什么会发生?
那么,你有没有通过调试器运行代码,看看究竟是抛出异常? – OldProgrammer 2014-08-30 19:49:29
您在写完文件后没有关闭文件,然后尝试重新打开它。关闭文件并添加一些错误检查。 – 2014-08-30 19:49:33
为什么你的最终循环忽略了一个大小? – 2014-08-30 19:53:46