C++: getline() 忽略前几个字符
在我的程序中,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;
}
.....}
In my program, fin
is an ifstream
object and song
is a string
.
When the program runs, it opens music.txt and reads from the file. I try to read each line with: getline(fin,song);
I've tried all variations of getline
but it keep ignoring the first 10 or so characters of each line before it starts picking up characters. For instance, if the song name is "songsongsongsongsongname," it might only pick up " songname."
Any ideas?
Here's the simplified code:
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;
}
.....}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
固定版本:
最重要的是我删除了
.eof()
的测试。您不能用它来测试您是否可以读取更多内容,也不能用它来测试先前的读取是否成功。验证早期操作是否成功可以通过检查失败标志来完成,或者最常见的是通过测试流本身来完成。A fixed version:
Most importantly I have removed the test of
.eof()
. You cannot use that for testing if you can read more and you also cannot use it for testing whether the previous read succeeded or not. Verifying that an earlier operation succeeded can be done by checking the fail flag, or most often by testing the stream itself.尝试用这种方法,
Give a try in this way,