【问题标题】:Why is nothing being written to the text file?为什么没有写入文本文件?
【发布时间】:2014-12-06 16:33:42
【问题描述】:

我正在尝试将歌曲信息写入文本文件,但没有写入任何内容。我试图将信息写入 onF 的部分正在运行,但文件为空白。顺便说一句,下面的代码是递归函数的一部分,这是前几个 if 语句的原因。有什么想法吗?

void writeToFile(int artist, int album, int song, int nA, int nAl, int nS)
{    
    ofstream onF("library.txt");
    if(song>=nS)
    {
        album+=1;
        song = 0;
    }
    if(album>=nAl)
    {
        artist++;
        album = 0;
        song = 0;
    }
    if(artist>=nA)
    {
        onF.close();
        return;
    }
    if(onF.is_open())
    {
         onF<<artists[artist].artistName<<'#';
         onF<<artists[artist].albums[album].albumName<<'#';
         onF<<artists[artist].albums[album].songs[song].songName<<'#';
         onF<<artists[artist].albums[album].songs[song].songLength<<endl;
         cout<<"RAN"<<endl;
    }
    else
        cout<<"File could not be opened."<<endl;
    song++;
    int numAlbums = artists[artist].numAlbums;
    int numSongs = artists[artist].albums[album].numSongs;
    writeToFile(artist, album, song, nA, numAlbums, numSongs);
 }

现在我已经开始工作了,我无法从文件中加载信息。它两次加载歌曲信息,第二次加载除歌曲标题之外的所有内容。循环运行两次:

if(inF)
{
    while(!inF.eof())
    {
        getline(inF, newArtist, '#');
        getline(inF, newAlbum, '#');
        getline(inF, newSong, '#');
        inF>>songLength;
        cout<<"CALLED"<<endl;
        addSong(newArtist, newAlbum, newSong, songLength, numArtists, 0, 0);      
    }
    inF.close();
    if(inF.is_open())
        cout<<"FAILED TO CLOSE"<<endl;
}

【问题讨论】:

  • 你能发布函数的签名以及你是如何调用它的吗?打开文件将删除所有现有内容,因此我假设您的程序确实写入了,只是在最后一次迭代中,它进入artist &gt;= nA 分支,然后将文件留空。
  • 能否请您包含整个函数和递归调用?
  • 我刚刚发布了整个函数

标签: c++ output ofstream


【解决方案1】:

您在函数入口处截断文件,因此最后一次调用将清除所有已写入的内容。

如果要追加,请添加 std::ios::app 标志

【讨论】:

  • 感谢您的帮助。不过我不想追加。我正在尝试将程序运行时输入的所有信息写入文件,当程序关闭并再次运行时,我想将所有信息加载回数组中。如果我手动写入文件,加载信息似乎有效。你有什么可以建议的吗?
  • 我尝试将输出文件作为参数传入,它起作用了。感谢您为我指明正确的方向!
  • 听起来需要在你的write函数中有一个for循环,所以你的write函数可以写入整个文件。但是,您的代码另有说明。一种选择是通过引用您的 write 函数来传递函数流。
猜你喜欢
  • 2019-09-13
  • 2013-10-01
  • 2021-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-02
  • 2020-10-07
  • 1970-01-01
相关资源
最近更新 更多