c++ - 从文件读取时无法使用 getline

标签 c++ file getline

我想从文件中读取数字,但在使用 getline 时遇到了问题。我有以下代码,我将发布重要的部分:

主要.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();
}

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

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

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

最佳答案

错误消息准确说明了问题所在。没有 getline 方法是 const char* 的成员。

您将 cstr 定义为 const char * cstr,然后尝试在其上调用 getline:cstr.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 .

关于c++ - 从文件读取时无法使用 getline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273730/

相关文章:

c++ - 使用 getline() 从文本文件中读入行并将 push_back 读入对象 vector

C++ 字符串数组搜索每个项目的输出

c++ - Boost 中有容器门面吗?

c++ - 使用谷歌测试将类型名和字符串传递给参数化测试

c++ - 如何正确初始化 std::set<std::string>?

java - 我如何使用java写入文本文件?

c - 如何在 C 编程中读取文件?

c++ - 在将 void* 转换为任何内容时,我应该使用 static_cast 还是 reinterpret_cast

c - `getline` 没有关闭管道就挂起[1]

linux - 如何使用 awk getline 清空文件