我是一名n00b C++程序员,我想知道如何从文本文件中读取特定的行。例如,如果我有一个包含以下行的文本文件:
1) Hello
2) HELLO
3) hEllO
我该如何阅读,比方说第二行,并将其打印到屏幕上?这就是我到目前为止所拥有的。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string sLine = "";
ifstream read;
read.open("input.txt");
// Stuck here
while(!read.eof()) {
getline(read,1);
cout << sLine;
}
// End stuck
read.close();
return 0;
}
注释部分中的代码就是我被卡住的地方。谢谢!!
发布于 2014-10-10 05:30:00
首先,你的循环条件是错误的。Don't use while (!something.eof())
.它不会像你想的那样工作。
你所要做的就是跟踪你在哪一行,一旦你读完第二行就停止阅读。然后,您可以比较行计数器,以查看是否成功到达第二行。(如果没有,则该文件包含的行数少于两行。)
int line_no = 0;
while (line_no != 2 && getline(read, sLine)) {
++line_no;
}
if (line_no == 2) {
// sLine contains the second line in the file.
} else {
// The file contains fewer than two lines.
}
发布于 2014-10-10 05:55:07
如果您不需要转换为字符串,请使用istream::read,请参阅此处http://www.cplusplus.com/reference/istream/istream/read/
https://stackoverflow.com/questions/26288145
复制相似问题