【问题标题】:getline() from a textfile errorgetline() 来自文本文件错误
【发布时间】:2016-01-01 01:12:49
【问题描述】:

对于学校实验室,我正在尝试从文本文件中获取行并显示它们。

我的开始:

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <playlist.h>

using namespace std;

void readLine(vector<string> playlist);
int totalTime();
void displayData();

int main()
{
    vector<string> playlist;

    readLine(playlist);
    totalTime();
    displayData();

    system("pause");

    return 0;
}
void readLine(vector<string> playlist)
{
    string currentline;
    int i = 0;
    while (getline("Playlist.txt", currentline) && !empty(currentline))
    {
        getline("Playlist.txt", playlist[i]);
        i = i + 1;
    }
}
int totalTime() 
{

}
void displayData()
{

}

似乎我误用了getline?两个“getline”有错误下划线:

获取线路

错误:没有重载函数“getline”的实例与 参数列表参数类型为:(const char [13], std::string)

我不知道错误的原因。

【问题讨论】:

  • getline 的文档肯定有解决问题的线索。你不明白什么?

标签: c++ text getline


【解决方案1】:

你没有错过getline 函数,你使用错了。

getline 需要 std::istream&amp;std::string&amp;。您需要打开一个std::ifstream 到该文件并将此流作为第一个参数传递。

请看这里: http://www.cplusplus.com/reference/string/string/getline/

【讨论】:

    【解决方案2】:

    像这样修改readLine()函数,要么传入playlist作为引用,要么返回playlist向量并将其移动到另一个向量中,因为除非你正在做一些你从代码中排除的事情,否则@987654325 @vector 会丢失

    vector<string> readLine(vector<string> playlist)
    {
        ifstream fin;
        fin.open("Playlist.txt");
        if (!fin) { 
            cerr << "Could not open file Playlist.txt" << endl;
            exit(1);
        }
    
        string currentline;
        int i = 0;
        while (getline(fin, currentline) && !empty(currentline))
        {
            getline(fin, playlist[i]);
            i = i + 1;
        }
    
        return playlist;
    }
    

    这是因为您尝试看起来的 getline 版本声明看起来像这样

    istream& getline (istream&  is, string& str);
    

    这需要对 istream 对象的引用作为第一个类型,如果您在此处看到 http://www.cplusplus.com/reference/fstream/ifstream/?kw=ifstream 的继承层次结构,您将看到 ifstream 类型的对象继承自 istream

    注意:正如在下面的 cmets 中指出的那样,您所做的似乎并不正确。我不知道我是怎么错过的。但你所做的似乎是错误的。如果您的意图是让 playlist 向量在文本文件中存储所有非空行,您应该有这样的循环

    string temp;
    while (getline(fin, temp)) {
        if (!temp.empty()) {
            lines.push_back(temp);
        }
    }
    

    另外还想检查你需要在其中编写该逻辑的空格

    【讨论】:

    • 不知道要不要指出原代码读取一行,如果不为空则丢弃,将下一行存入播放列表,不管是不是是否为空(也忽略 EOF)。这可能不是预期的设计。否则,很好的答案。
    • 另外,上面的方法实际上并没有做任何事情,因为一旦方法完成,playlist 什么也做不了。
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2012-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    相关资源
    最近更新 更多