从文件中读取时无法使用getline

时间:2013-11-28 19:40:12

标签: c++ file getline

我想从文件中读取数字并且我遇到了问题。我有以下代码,我将发布重要的部分:

的main.cpp

int main() {
    GrafNoEtiquetat Graf;
    ifstream f_ent;
    ofstream f_sort;
    string str;

    cout << "Introdueix el nom del fitxer a llegir." << endl;
    cin >> str;
    char *cstr=new char[str.size()+1];
    strcpy(cstr, str.c_str());
    f_ent.open(cstr);
    if(f_ent.fail()) cerr << "El fitxer no s'ha pogut obrir." << endl;
    else {
        Graf(cstr);
        unidireccional(Graf);
        delete [] cstr;
        cout << "Introdueix el nom del fitxer de surtida" << endl;
        cstr = new char [str.size()+1];
        strcpy(cstr, str.c_str());
        f_sort.open(cstr);
        if(f_sort.fail()) cerr << "El fitxer no s'ha creat." << endl;
        else Graf.escriureGraf(f_sort);
    }
    return 0;
}

这是使用const char * cstr:

创建Graf的函数
GrafNoEtiquetat::GrafNoEtiquetat(const char * cstr) {
    char c[1000];
    int n1, n2;
    cstr.getline(c,80);
    while(c!="#") {
        nNodes++;
        cstr.getline(c,80);
    }
    arestes.resize(nNodes+1);
    while(!cstr.eof()) {
        cstr >> n1;
        cstr >> n2;
        afegirAresta(n1, n2);
    }
    cstr.close();
}

我在getline,cstr.eof()中使用'cstr'的所有行中都出现错误,当我读取n1和n2以及我想要关闭文件时。 错误类似于以下内容:

error: request for member 'getline' in 'cstr', which is of non-class type 'const char*'

我不知道为什么会发生这种情况,有什么线索?

1 个答案:

答案 0 :(得分:3)

错误消息说明问题是什么。没有getline方法可以成为const char*的成员。

您将cstr定义为const char * cstr,然后尝试在其上调用getlinecstr.getline(c,80);。您应该使用它来阅读istream不是字符数组中的内容。

如果您想按自己的方式行事,请按以下步骤操作:

GrafNoEtiquetat::GrafNoEtiquetat(const char * cstr) {
    ifstream inputFile(cstr);
    char c[1000];
    int n1, n2;
    inputFile.getline(c,80);
    while(c!="#") {
        nNodes++;
        inputFile.getline(c,80);
    }
    arestes.resize(nNodes+1);
    while(!inputFile.eof()) {
        inputFile >> n1;
        inputFile >> n2;
        afegirAresta(n1, n2);
    }
    inputFile.close();
}

您还应该检查文件是否正确打开。为此,请使用ifstream::is_open