试图用C++编写一个只读取第一列数据并跳到下一行的类
Trying to write a class in C++ that only reads in the first column of data and skips to the next line
这可能是一个非常简单的问题,但我没有找到任何例子来指导我。我正在尝试用C++编写一个类,它可以读取一个文本文件,其中数据列(float、char、int等)用空格分隔。我希望类能够忽略某些列并读入指定的列。目前,我正在尝试一列和两列格式,并从中取得进展。下面列出了一个测试输入文件的简短示例。
103.816
43.984
2214.5
321.5
615.8
8.186
37.6
我第一次尝试编写代码来读取一列数据是微不足道的,看起来是这样的。
void Read_Columnar_File::Read_File(const std::string& file_name)
{
int i;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()) {
std::istream_iterator<float> start((inp)), end;
std::vector<float> values(start,end);
for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
在我的下一次尝试中,我尝试只阅读两列格式的一列,如下面所示的输入。这些数字只是这个例子的组成部分
103.816 34.18
43.984 21.564
2214.5 18.5
321.5 1.00
615.8 4.28
8.186 1.69
37.6 35.48
我稍微修改了代码格式,使其看起来像下面的示例。在inp>>语句之后,我使用了一个简短的伪代码来说明我试图让代码在阅读第一列后跳到下一行。我的问题是"我如何让代码只读取第一列,然后跳到下一行,再次读取第一列数据,并使其一直这样做,直到文件结束?"提前感谢您提供的任何建议。
void Read_Columnar_File::Read_File(const std::string& file_name)
{
int i;
float input;
std::vector<float> values;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()) {
for(i=0; i < 7; i++) {
inp >> input >> \ - At this point I want the code to skip to the next
\ line of the input file to only read the first column
\ of data
values.push_back(input);
}
for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
您可以使用成员函数ignore()
丢弃所有字符,直到下一行。我还将修复您的代码,使其使用基于提取成功的for()
循环,这样您的代码将适用于任何数量的列,而不仅仅是7:
for (float input; inp >> input; values.push_back(input))
{
inp.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
}
当您只想读取一行的一部分,并跳过该行的其余部分时,一个简单的起点是:
- 将整行读入字符串
- 将整个字符串放入istringstream
- 分析出你关心的部分
- 重复
通常,我发现这比从文件中读取数据时在读取和忽略数据之间交替的方法更容易概括。
相关文章:
- 查找矩阵C++中每一列和每一行的最小和最大元素
- 如何在C++中获取二维数组中最少的一列数?
- 我无法将数据从数据网格列传输到 C# 中的数组以获取文本框建议收集数据
- 如何允许用户选择何时停止三列中的每一列的旋转
- 从我的2d数组中的一列返回的字符串值被压缩为一个字符串(在Mac os上打开Windows txt文件)
- 在犰狳立方体中添加一列 1 的有效方法
- 在二维向量的每一列中查找最大值
- 只有一列适合其内容大小,而另一列则拉伸
- 如何将单独的数组分组在一起(类似于按一列对表进行排序)
- C++ 最后一列中的直方图错误
- 添加两个矩阵会打印一列垃圾数据 c++
- C 特征:通过参考将矩阵的一列传递到函数中
- 仅制作一列qtreewidget可编辑//故障排除
- 在 QTableView 中仅对一列进行排序,而不对其他列进行排序.独立列
- 按列对CSV文件进行排序,并与C 中的另一列进行比较
- MySQL 使用一组列中的数据更新列,以非零值为准
- 读取数据文件并将每一列分配给各个数组
- 数据排序依据是哪一列,QTableWidget
- 如何从文本文件中保存一列数据到c++中的数组
- 从CSV文件中读取一列数据