0

在我的程序中,fin是一个ifstream对象并且song是一个string.

当程序运行时,它会打开 music.txt 并从文件中读取。我尝试阅读每一行:getline(fin,song);

我已经尝试了所有变体,getline但它在开始拾取字符之前一直忽略每行的前 10 个左右字符。例如,如果歌曲名称是“songsongsongsongsongname”,它可能只会选择“songname”。

有任何想法吗?

这是简化的代码:

 void Playlist::readFile(ifstream &fin, LinkedList<Playlist> &allPlaylists, LinkedList<Songs*> &library) 
{
    string song;
    fin.open("music.txt");  
    if(fin.fail())          
    {
        cout << "Input file failed. No saved library or playlist. Begin new myTunes session." << endl << endl;
    }
    else
    {
        while(!fin.eof() && flag)
        {
                getline(fin, song);     
                cout << song << "YES." << endl;
                }
.....}
4

2 回答 2

0

试试这个方法,

...
else
{
    while(fin)
    {
        getline(fin, song);    //read first
        if(!fin.eof() && flag) //detecting eof is meaningful here because
        {                      //eof can be detected only after it has been read
            cout << song << "YES." << endl;
        }
    }
}
于 2013-04-04T08:45:29.727 回答
0

固定版本:

void Playlist::readFile(std::string const& filename, ...) {
    std::ifstream fin(filename.c_str());
    if (!fin) throw std::runtime_error("Unable to open file " + filename);
    for (std::string song; std::getline(fin, song); ) {
        ...
    }
}

最重要的是,我删除了.eof(). 你不能用它来测试你是否可以阅读更多,你也不能用它来测试之前的阅读是否成功。可以通过检查失败标志来验证先前的操作是否成功,或者通常通过测试流本身来完成。

于 2010-03-11T01:58:53.327 回答