有没有办法请求在 C++ 中读取文本文件的某个位置?

Is there a way to request a certain location of a text file to be read in C++?

我使用的是两行文本文件。每行都有几千个数字(带符号的双打)。所以它看起来像这样:

X.11   X.12   X.13   ...
X.21   X.22   X.23   ...

对于我程序的每个循环,我想从每一行读取一个数字。因此,对于循环的第一次迭代,它将是 X.11 & X.21,对于第二次迭代,它将是 X.12 & X.22,依此类推。我不需要存储值。

预期输出:

X.11  X.21
X.12  X.22
X.13  X.23

如何在 C++ 中完成此操作? 我通常使用 fstream 读取文件,并使用 std::getline(file, line) 逐行读取文件。我如何从每一行读取一个数字?

如果您已经阅读了使用 std::getline(file, line) 的行,您可以获取您获得的字符串,并将其标记化 char* p = strtok (yourline, " "); 然后 *p 将在第一行产生 X.11,并且对于下一个,您只需再次调用 strtok

对于 fstream,您可以使用 tellgseekg 来存储和恢复流中的位置。但是,我还没有证实它们与格式化输入一起工作得很好。

假设您不想将结果存储在内存中并且它只有两行,另一种解决方案是打开文件两次 - 并将其视为从两个不同文件中读取行。

I don't need to store the values.

当然可以,但是如果你这样做了,比如在两个双精度数组中,那么你的循环将是微不足道的,并且比常规磁盘读取快得多。两个包含几千个双精度值的数组可能比您想象的要少内存使用。 1 Mb 的 RAM 可以包含 131072 个八字节双精度数。

I assume you need: I want to read one number from each line.
otherwise comment me; I will delete the answer.

使用 2 个并行流读取 文件

std::ifstream input_file_stream_1( "file" );
std::ifstream input_file_stream_2( "file" );

std::string line_1;
std::string line_2;
std::string ignore;
std::getline( input_file_stream_2, ignore );    // ignore the whole first line

for( ; input_file_stream_1 >> line_1 && input_file_stream_2 >> line_2; ){
    std::cout << line_1 << " and " << line_2 << '\n';
}

input_file_stream_1.close();
input_file_stream_2.close();  

输入:

X.11   X.12   X.13   ...
X.21   X.22   X.23   ...

输出:

X.11 and X.21
X.12 and X.22
X.13 and X.23
... and ...

它是如何工作的?
由于您的文件只有 2 行,所以我在同一个文件上使用了两个 input_stream。其中一个用于第一行,另一个用于第二行。但是在进行for循环之前。 input_file_stream_2 读取第一行并且不需要使用它,因为 input_file_stream_1 想要读取它。因此,在忽略该行(第一行)之后。 input_file_stream_1 有第 1 行,input_file_stream_2 有第 2 行。现在你有两行流。在 for 循环中,(或 while )您可以通过 >> operator

提取每个文本

或使用 std::regex 库:

std::ifstream input_file_stream( "file" );

std::string line_1;
std::string line_2;
std::getline( input_file_stream, line_1 );
std::getline( input_file_stream, line_2 );

std::regex regex( R"(\s+)" );
std::regex_token_iterator< std::string::iterator > begin_1( line_1.begin(), line_1.end(), regex, -1 ), end_1;
std::regex_token_iterator< std::string::iterator > begin_2( line_2.begin(), line_2.end(), regex, -1 ), end_2;

while( begin_1 != end_1 && begin_2 != end_2 ){
    std::cout << *begin_1++ << " and " << *begin_2++ << '\n';
}

input_file_stream.close();  

输出:(同上)

X.11 and X.21
X.12 and X.22
X.13 and X.23
... and ...

注意:
有不止一种方法可以做到这一点