按变量数组中的列将一组整数从文本文件读入
read in a set of integers from a text file into by column in to variable arrays
如果我有一个文本文件,看起来像:
4
1 2 3
4 5 6
7 8 9
10 11 12
我想把每列数字读入一个变量x、y和z。所以在阅读之后,z=[3,6,9,12]。
如何解析文本文件以将每列的每一行存储在其自己的变量中?
所以,也许可以将整个文本文件存储为每行带有"/n"的字符串,然后为每行解析x=string[i],y=string[i+1],z=string[i+2]?或者类似的东西。
我认为必须有更好的方法来做到这一点,尤其是当n很大的时候。
~(edit)顶部的第一个数字(本例中为4)决定了文本文件的行数。因此,如果我设置n=4,那么就有一个for循环:for(I=0;I
一次读取一个项目,将每个项目添加到适当的数组:
std::vector<int> x,y,z;
int xx, yy, zz;
while(std::cin >> xx >> yy >> zz) {
x.push_back(xx);
y.push_back(yy);
z.push_back(zz);
}
编辑:响应添加的要求
int n;
if( !( std::cin >> n) )
return;
std::vector<int> x,y,z;
int xx, yy, zz;
while(n-- && std::cin >> xx >> yy >> zz) {
x.push_back(xx);
y.push_back(yy);
z.push_back(zz);
}
寻求"通用"解决方案(其中n
是列数)。在这种情况下,与其单独使用向量变量,不如使用向量中的向量:
std::fstream file("file.txt", ios_base::in);
std::vector< std::vector<int> > vars(n, vector<int>(100));
int curret_line = 0;
while (!file.eof())
{
for (int i=0; i<n; ++i)
{
file >> vars[i][current_line];
}
++current_line;
// if current_line > vars[i].size() you should .resize() the vector
}
编辑:根据下方的评论更新循环
int i=0, current_line = 0;
while (file >> vars[i][current_line])
{
if (i++ == n)
{
i = 0;
++current_line;
}
}
这里有一种方法,包括一些基本的错误检查。我们将把小于或大于3个整数的行视为错误:
#include <fstream>
#include <string>
#include <sstream>
#include <cctype>
std::ifstream file("file.txt");
std::string line;
std::vector<int> x,y,z;
while (std::getline(file, line)) {
int a, b, c;
std::istringstream ss(line);
// read three ints from the stream and see if it succeeds
if (!(ss >> a >> b >> c)) {
// error non-int or not enough ints on the line
break;
}
// we read three ints, now we ignore any trailing whitespace
// characters and see if we reached the end of line
while (isspace(ss.peek()) ss.ignore();
if (ss.get() != EOF) {
// error, there are more characters on the line
break;
}
// everything's fine
x.push_back(a);
y.push_back(b);
z.push_back(c);
}
相关文章:
- 如何从一组具有从左到右优先级的整数值创建有序整数键?
- 编写所需的代码以创建动态一维整数数组
- 我如何将一组整数集变成C 中的3D矢量
- 给定一组正整数 <=k 及其 n 个子集,找到哪些子集对给出原始集合的并集
- 如何将字符串形式的日期 ( "Dec 25, 2012" ) 转换为一组整数 (12/25/12)?
- 最长的子序列,其元素构成一组递增的整数
- 如何查找具有一组整数的函数的'max absolute sum'
- 给定一个整数数组和一个数k,计算长度为k的每个子数组的最大值
- C++将一组整数变量映射到值的有效方法
- 在C++中生成一组整数的排列.获取分段错误
- 给定一组 12 个整数,如何递归生成所有可能的 4 组 3 个整数?C++
- 从另一组整数中有效地删除一组整数
- 按变量数组中的列将一组整数从文本文件读入
- 保存一组整数的最佳方法
- 计算一组关系的整数映射的更有效的算法
- 如何将一维整数数组从 QML 发送到C++
- 我需要标记一组匹配的整数,以便用分数进行数学检查
- 如何在C++中添加一组整数
- 将一组整数读取为C++中的字符串
- 如何在c++中创建一组非标准顺序的整数