我真的不知道发生分割错误的位置。这是我的代码如下。
#include <iostream>
#include <stdlib.h>
#include <string>
#include <fstream>
#include <list>
#include <iomanip>
#include <stdexcept>
using namespace std;
class isbn
{
private:
string *code;
int digit;
isbn *current, *next;
public:
//constructor
isbn(): code(NULL), digit(0) { }
//copy constructor
isbn(const isbn &other):
code(new string[other.digit]),
digit(other.digit)
{
for(int i=0; i < digit; i++)
code[i] = other.code[i];
}
//destructor
~isbn()
{
if(digit>0) delete [] code;
}
//set up the private values
void setCode(char *temp, int num);
void setDigit(const int &num);
//return the value of the pointer character
const string &getCode(int num) const;
const unsigned int getDigit() const;
//assignment operator
isbn operator = (const isbn &other)
{
code = new string[other.digit];
digit = other.digit;
for(int i=0; i < digit; i++)
code[i] = other.code[i];
return *this;
}
//equal operator for a digit
bool operator == (const isbn &other) const
{
return code == other.code;
}
};
const string& isbn::getCode(int num) const
{
return code[num];
}
const unsigned int isbn::getDigit() const
{
return digit;
}
void isbn::setCode(char *temp, int num)
{
if (num<0 || num >= digit)
{
throw out_of_range("error occurred from setCode");
}
code[num] = temp;
}
void isbn::setDigit(const int &num)
{
digit = num;
}
void extIsbn_in_file(list<isbn> &isbns, const string &filename)
{
ifstream filein;
filein.clear();
filein.open(filename.c_str());
if(!filein)
{
cout << "Unable to open file to read \n";
exit(0);
}
cout << "\n file : " << filename << "\n";
cout << "\n";
char *contents;
isbn aisbn;
list<isbn>::iterator isbnitr;
isbnitr = isbns.begin();
int count = 0;
while(!filein.eof())
{
filein.getline(contents, '\n');
cout << contents << '\n';
aisbn.setCode(contents, count);
aisbn.setDigit(count);
isbns.push_back(aisbn);
count++;
}
filein.close();
}
int main(int argc, char *argv[])
{
if(argc > 0)
{
if(argc != 2)
{
cout << "Error: the num of arguments should be 2";
exit(0);
}
list<isbn> code;
extIsbn_in_file(code, argv[1]);
}
else
{
cout << "invalid number of argument!! \n";
exit(0);
}
return 0;
}
只需猜测下面的代码就会拖动分段错误错误。并且不确定我设置的构造函数是否正确。如果错了,我该如何解决?
while(!filein.eof())
{
filein.getline(contents, '\n');
cout << contents << '\n';
aisbn.setCode(contents, count);
aisbn.setDigit(count);
isbns.push_back(aisbn);
count++;
}
答案 0 :(得分:1)
提示:filein.getline(contents, '\n');
没有按照您的预期执行操作。我没有故意提供完整的解决方案,它对你学习没有帮助,而是阅读:http://www.cplusplus.com/reference/istream/istream/getline/
答案 1 :(得分:1)
你需要初始化char *内容;到堆上分配的一些内存。或者使用std :: string。 谢谢@Jaochim