c ++如何将文本文件中的一行分成两行,然后将每一行存储到两个不同的数组中?

c++ How split one line into two from a text file then store each into two different arrays?

说,我在文本文件中有这个

1   15
2   20
3   25
4   30
5   35

如何拆分它们以便将第一列存储在向量 x 上,将第二列存储在向量 y 上?

我将从最简单的解决方案开始,然后逐渐将其细化为使用流迭代器等。然后您将对 C++(模板)库的强大功能产生印象。

伪代码:

Open file
Declare vectors x and y
while ( not end-of-file )
{
    int tmp1, tmp2;
    stream into tmp1 and tmp2
    check stream status for format violations
    add tmp1 to x, add tmp2 to y
}

假设您的数据是干净的并且您知道如何打开文件:

while(std::cin >> x >> y){
    vectorx.pushback(x);
    vectory.pushback(y);
}

std::cin 不读取空格。您可以使用 std::cin 从文件中读取数据,只要您的数据按可预测的方式组织并且您知道数据类型。否则,您可能需要考虑使用 std::getline(),例如。