【问题标题】:Can't use getline when reading from a file从文件读取时无法使用 getline
【发布时间】:2013-11-28 19:40:12
【问题描述】:

我想从文件中读取数字,但我遇到了 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();
}

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

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

不知道为什么会这样,有什么线索吗?

【问题讨论】:

    标签: c++ file getline


    【解决方案1】:

    错误消息准确地说明了问题所在。没有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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-27
      • 2015-01-21
      • 2011-05-03
      • 2012-06-17
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多