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

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

本文关键字:存储 然后 两个 数组 拆分 文本 文件 c++ 一行 两行      更新时间:2023-10-16

比方说,我在一个文本文件上有这个

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()

相关文章: