C ++ - 输出文件中打印的不需要的字符

时间:2010-03-11 08:09:34

标签: c++ printing ofstream

这是我正在进行的计划的最后一部分。我想输出一个表格列表的歌曲cout。然后我想将一个特殊格式的歌曲信息列表输出到fout(稍后将用作输入文件)。

打印到cout效果很好。问题是在打印到fout时会增加大量的额外字符。

有什么想法吗?

以下是代码:

    void Playlist::printFile(ofstream &fout, LinkedList<Playlist> &allPlaylists, LinkedList<Songs*> &library)
{
 fout.open("music.txt"); 
 if(fout.fail())   
 {
  cout << "Output file failed. Information was not saved." << endl << endl;
 }
 else
 {
  if(library.size() > 0)
   fout << "LIBRARY" << endl;
  for(int i = 0; i < library.size(); i++)           // For Loop - "Incremrenting i"-Loop to go through library and print song information.
  { 
   fout << library.at(i)->getSongName() << endl;     // Prints song name.
   fout << library.at(i)->getArtistName() << endl;     // Prints artist name.
   fout << library.at(i)->getAlbumName() << endl;     // Prints album name.
   fout << library.at(i)->getPlayTime() << " " << library.at(i)->getYear() << " ";
   fout << library.at(i)->getStarRating() << " " << library.at(i)->getSongGenre() << endl;   
  }
  if(allPlaylists.size() <= 0)
   fout << endl; 
  else if(allPlaylists.size() > 0)  
  {
  int j;
  for(j = 0; j < allPlaylists.size(); j++)           // Loops through all playlists.
  {
   fout << "xxxxx" << endl;
   fout << allPlaylists.at(j).getPlaylistName() << endl;
   for(int i = 0; i < allPlaylists.at(j).listSongs.size(); i++)          
   {
    fout << allPlaylists.at(j).listSongs.at(i)->getSongName();
    fout << endl;
    fout << allPlaylists.at(j).listSongs.at(i)->getArtistName();
    fout << endl;
   } 
  }
  fout << endl;
  }
 }
}

以下是music.txt(fout)的输出示例:

LIBRARY
sadljkhfds
dfgkjh
dfkgh
3 3333 3 Rap
sdlkhs
kjshdfkh
sdkjfhsdf
3 33333 3 Rap
xxxxx
PayröÈöè÷÷(÷H÷h÷÷¨÷È÷èøø(øHøhøø¨øÈøèùù(ùHùhùù¨ùÈùèúú(úHúhúú¨úÈúèûû(ûHûhûû¨ûÈûèüü(üHühüü¨üÈüèýý(ýHýhý
! sdkjfhsdf!õüöýÄõ¼5!
sadljkhfds!þõÜö|ö\
 þx þ  þÈ þð ÿ ÿ@ ÿh ÿ ÿ¸ ÿà  0 X  ¨ Ð ø
    enter code here
    enter code here

1 个答案:

答案 0 :(得分:5)

很可能,你的一个方法返回一个不正确的char *字符串(不是以null结尾)。

编辑:实际上,不只是一个:getPlaylistName(),getSongName()和getArtistName()。