[英]C++: getline() ignoring first several characters
在我的程序中, 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;
}
.....}
以這種方式嘗試一下,
...
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;
}
}
}
固定版本:
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()
的測試。 如果您可以閱讀更多內容,則不能將其用於測試,也不能將其用於測試先前的讀取是否成功。 可以通過檢查失敗標志來驗證較早的操作是否成功,或者通常可以通過測試流本身來進行驗證。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.