在读取文件(ifstream)时,有什么方法可以指示它换行吗?
在读取文件(ifstream)时,有什么方法可以指示它换行吗?
例如,我希望发生这种情况:
myfile>>array[1]>>array[2]>>endl;
显然,“endl”是不允许的。 还有其他方法可以做到这一点吗?
编辑——感谢大家的快速回复!
从一个文本文件中,我尝试将该文件中的两个字符串存储到数组中,然后对下一行执行相同的操作(或者直到我需要时,使用 for 循环)
使用字符串对我来说很重要,因为它将让我的未来程序灵活很多。
While reading a file (ifstream), is there any way to direct it to make a new line?
For instance, I would like for THIS to happen:
myfile>>array[1]>>array[2]>>endl;
Obviously, the "endl" just isn't allowed. Is there another way to do this?
Edit---thanks for the quick responses guys!
From a text file, I'm trying to store two strings from that file into arrays and then do the same with the next line (or until I desire, using a for loop)
Using strings is important to me as it will make my future program a lot more flexible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用 std::getline 将一行读入内存流,然后从中获取两个字符串。
Use
std::getline
to read a line into a memory stream, then get the two strings from that.读取您的两项,然后调用
myfile.ignore(8192, '\n')
Read your two items, then call
myfile.ignore(8192, '\n')
我不知道这个问题是什么意思。 这是将文件的所有行读入字符串向量的简单方法。 如果你先这样做,做你想做的事可能会更容易。
现在您可以说
lines[4]
来获取第五行,或者使用lines.size()
来找出有多少行。I have no idea what this question means. Here's a simple way to read all the lines of a file into a vector of strings. It might be easier to do what you want to do if you do this first.
Now you can say
lines[4]
to get the fifth line, orlines.size()
to find out how many lines there were.这应该有效:
早期答案的定制版本。
This should work:
Customized version of an earlier answer.
几个选项:
您可以使用忽略。
或者您可以将每一行读入字符串流
请注意:数组索引从 0 开始。
Several options:
You can use ignore.
Or you can read each line into as string stream
Please note: Array indexing starts at 0.