【发布时间】:2015-09-24 16:47:55
【问题描述】:
问题描述
我有一个包含一组行的文件。一个
文件 1:
"Hello How are you"
"The cat ate the mouse"
基于用户输入的行的开头和结尾。我想转到文件中的每一行并提取它。
例如,如果用户输入 1 、 17 ,那么我必须转到 1 行,其大小为 17 字符。他可以给出文件中的任何行号。
我阅读了以下答复Read from a specific spot in a file C++。但我真的不明白。为什么线的大小必须相同?如果我有关于文件中每一行的开头和结尾的信息。为什么不能直接访问?
源代码
我尝试使用受Read Data From Specified Position in File Using Seekg 启发的以下代码,但为什么无法提取行?
#include <fstream>
#include <iostream>
using namespace std::
void getline(int, int, const ifstream & );
int main()
{
//open file1 containing the sentences
ifstream file1("file1.txt");
int beg = 1;
int end = 17;
getline(beg,end, file1);
beg = 2;
end = 20;
getline(beg,end, file1);
return 0;
}
void getline(int beg, int end, const ifstream & file)
{
file.seekg(beg, ios::beg);
int length = end;
char * buffer = new char [length];
file.read (buffer,length);
buffer [length - 1] = '\0';
cout.write (buffer,length);
delete[] buffer;
}
【问题讨论】:
-
删除
using namespace std::(不会编译顺便说一句,我怀疑在你的真实代码中你有using namespace std;)。 -
所以第一个数字告诉您要在文件中读取哪一行,第二个数字告诉您要从该行读取多少个字符?您当前代码的结果是什么?运行时会发生什么?
-
"如果我有关于文件中每一行的开头和结尾的信息" 那么是的,可以直接查找任意行。但是您的代码并未显示您拥有该信息。
-
额外提示:您将无法从 const fstream 中读取。如果您的编译器允许这样做并为您构建可执行文件,请获取一个新的编译器。