【问题标题】:C++ - Unwanted characters printed in output fileC++ - 在输出文件中打印不需要的字符
【发布时间】:2023-05-20 19:47:01
【问题描述】:

这是我正在处理的程序的最后一部分。我想将歌曲的表格列表输出到 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

【问题讨论】:

    标签: c++ printing ofstream


    【解决方案1】:

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

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

    【讨论】:

    • ...或一个悬空指针(指向堆栈、已释放的内存、已移动的内存 [例如 realloc'ed]),或者它们返回由此类指针构建的 std::string .
    • @Gabe 只需返回一个有效的以 null 结尾的 char * 字符串或使用 std::string。