c++如何从.csv文件中读取值并将其存储在矢量中
c++ How can I read values from a .csv file and store them in a vector?
我在Windows7上使用Code::Blocks从.cpp文件中制作小.exe,我是一个初学者(对不起!)
这是今天的问题:
我有一个.csv文件,其中包含用分号分隔的长整数(从0到2^16),并列为一系列水平行。
我将在这里举一个简单的例子,但事实上,文件的大小可能高达2Go。
假设我的文件wall.csv
在文本编辑器(如Notepad++
:)中显示为这样
350;3240;2292;33364;3206;266;290
362;314;244;2726;24342;2362;310
392;326;248;2546;2438;228;314
378;334;274;2842;308;3232;356
奇怪的是,它在窗口notepad
中显示为这样
350;3240;2292;33364;3206;266;290
362;314;244;2726;24342;2362;310
392;326;248;2546;2438;228;314
378;334;274;2842;308;3232;356
不管怎样,
假设我知道并将在3个float
变量中声明文件中的列数、行数和值。
int col = 7; // amount of columns
int lines = 4; // amount of lines
float x = 0; // a variable that will contain a value from the file
我想要:
- 创建
vector <float> myValues
- 对csv第一行中的每个值执行
myValues.push_back(x)
- 对csv第2行的每个值执行
myValues.push_back(x)
- 对第三行中的每个值执行
myValues.push_back(x)
。。。等等
,直到文件完全存储在向量myValues中
我的问题:
我不知道如何将csv文件中的值依次分配给变量x
。
我该怎么做?
好的,这个代码工作(相当慢,但还好!):
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int col = 1221; // amount of columns
int lines = 914; // amount of lines
int x = 0; // a variable that will contain a value from the file
vector <int> myValues;
int main() {
ifstream ifs ("walls.tif.csv");
char dummy;
for (int i = 0; i < lines; ++i){
for (int i = 0; i < col; ++i){
ifs >> x;
myValues.push_back(x);
// So the dummy won't eat digits
if (i < (col - 1))
ifs >> dummy;
}
}
float A = 0;
float B = col*lines;
for (size_t i = 0; i < myValues.size(); ++i){
float C = 100*(A/B);
A++;
// display progress and successive x values
cout << C << "% accomplished, pix = " << myValues[i] <<endl;
}
}
将文本数据放入stringstream
并使用std::getline
。
它需要一个可选的第三个参数,即"end-of-line"
字符,但您可以使用;
而不是真正的end of line
。
呼叫while (std::getline(ss, str, ';')) {..}
并且每个循环将文本放入CCD_ 16中。
然后,您需要转换为数字数据类型并推送为向量,但这将使您开始。
另外,为什么要使用floats
来表示列数和行数?
它们是整数值。
尝试使用C++标准模板库的输入操作。
制作一个伪字符变量来吃掉分号,然后将cin数字放入x变量中,如下所示:
char dummy;
for (int i = 0; i < lines; ++i){
for (int i = 0; i < col; ++i){
cin >> x;
myValues.push_back(x);
// So the dummy won't eat digits
if (i < (col - 1))
cin >> dummy;
}
}
要这样做,你可以重定向你的csv文件,从命令行输入,如下所示:
yourExecutable.exe < yourFile.csv
要循环通过充满数据的矢量:
for (size_t i = 0; i < myVector.size(); ++i){
cout << myVector[i];
}
上面,size_t类型由STL库定义,用于抑制错误。
如果您只想使用一次值,并在使用时将其从容器中删除,那么最好使用std::queue容器。通过这种方式,您可以使用front()查看front元素,然后使用pop()将其移除。
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 将从格式化文本文件读取的文本数据存储到链表
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 读取文件并将其存储在unordered_map中时出现问题
- 如何读取 TXT 文件并仅将 int 存储在 C 中
- 读取和存储 CSV 数据
- 读取文件并将其内容存储到 2-D 数组C++中
- 从文本文件读取,然后将项目存储到列表中
- 如何读取文件并将该文件分类为不同类型的数据,这些数据都存储在结构中的特定数组中
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 如何从excel文件中读取数据并存储到变量中?
- 如何在不知道大小的情况下读取文本文件并存储到数组中
- 如何在C++中读取并立即丢弃一些数据,而不存储这些数据
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 从文件中读取后,将分号分隔的整数存储到数组中
- 是防止原子存储部分读取所必需的"memory_order_relaxed"
- 如何将 numpy 二维数组作为一种可以用C++读取的二进制格式存储在磁盘上
- 从文件中读取选定的行范围并存储到数组中
- 如何从输入文件中读取字符并将其存储到向量中?
- 引发未经处理的异常:简单 C++ 程序中的读取访问冲突,动态增加数组长度以存储数字