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()
。
相关文章:
- 如何存储用户输入的所有数据,然后在他们想要查看所有数据时显示它们
- 使用 std::map 存储在 std::any 中,然后通过 std::any_cast 访问
- 从文本文件读取,然后将项目存储到列表中
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- 是否可以将多个结构作为一个数据包存储在一个函数中,然后传递给其他函数并在那里提取?
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- 如何存储多个用户输入,然后以C++显示它们
- 如何在每次循环迭代期间生成向量,存储数据,然后删除该向量?
- 正在使用放置-new,复制存储,然后访问值未定义的行为
- 如何使类函数返回数组,然后将其调用并存储在 main 中
- 如果结果存储在变量中forward_as_tuple然后在 std::apply 中使用之前丢失右值引用
- 如何在给定任意数量的整数的情况下创建一个唯一键?并使用该键存储,然后从地图中查找
- 将25个甚至整数存储到一个名为intlist的整数阵列中,然后在屏幕上显示数组,并在屏幕上显示名为fivintegers
- 如何修改数组,从中删除空格,然后将其存储在新数组中
- 如何将元素的索引从2D数组存储到1D数组中,然后交换这些值
- 获取一个输入字符串,将其转换为其十六进制值,然后将其十六进制存储为 int
- 从数组中获取值并计算平均值,然后存储在数组中
- 将具有任意参数和占位符的函数存储在类中,然后再调用它
- 存储在基本分配中,然后调用基本功能
- C 将向量转换为2个十六进制,然后将其存储在字符串中