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

C++ c++;如何将文本文件中的一行拆分为两行,然后将每行存储到两个不同的数组中?,c++,vector,C++,Vector,喂,我有一个文本文件 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

喂,我有一个文本文件

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()
,例如。

std::getline(istream&is,string&str,char-delim)
因为您使用了所有的“流迭代器”等等,所以知道OP不知道您在说什么。您的while循环不应搜索eof。有多种方法可以做到这一点,但请告诉我为什么检查eof在这里如此糟糕。