在读取.csv时将数组类型字符串转换为double
converting array type string to double with .csv read
我正在接受一个.csv文件,其中包含字符串并将一定范围内的所有内容转换为double类型。我的目标实际上只是捕获第四列,但如果我想捕获更多,将它们全部作为一个矩阵似乎是最好的方法。但是,当我将字符串类型转换为double类型时,这些转换对我来说没有意义。
表示"24 Month"的字符串将被转换为值24。但是,表示"4.35183217"的字符串将被转换为0(实际上它是一个非常小的负数)。为什么会这样?
见这里的输入查看这里的输出
double data[38][27];
std::ifstream file("YC Rate Levels.csv");
for (int row = 0; row < 38; ++row)
{
std::string line;
std::getline(file, line);
if (!file.good())
break;
std::stringstream iss(line);
for (int col = 0; col < 27; ++col)
{
std::string val;
std::getline(iss, val, ',');
if (!iss.good())
break;
std::stringstream convertor(val);
convertor >> data[row][col];
}
}
std::cout << "Col 3" << " - " << "Col 4" << std::endl;;
for (int i = 0; i < 38; ++i)
{
std::cout << data[i][3] << " - " << data[i][4] << std::endl;
}
std::cin.clear(); // reset any error flags
std::cin.ignore(32767, 'n'); // ignore any characters in the input buffer until we find an enter character
std::cin.get(); // get one more char from the user
return 0;
您的数据未初始化且未定义,这就是为什么它默认为一些小数字。您可以初始化如下:double data[38][27]={0};
或更好,但使用std::vector
"abc", "123", "345"
有一个额外的空格或引号。字符串表示为""345""
,不转换为345.00
。
使用std::stod
而不是stringstream
,当输入不能转换时将抛出异常。例子:
try
{
double temp = std::stod(val);
}
catch (...)
{
std::cout << "bad input: " << val << std::endl;
}
使用下面的函数从文本的左/右删除引号和空格:
void trim(std::string& s, const char* t)
{
s.erase(0, s.find_first_not_of(t));
s.erase(s.find_last_not_of(t) + 1);
}
把它放在一起:
std::vector<std::vector<double>> data;
std::string line;
while(std::getline(file, line))
{
std::vector<double> row;
std::stringstream iss(line);
std::string val;
while (std::getline(iss, val, ','))
{
trim(val, " "");
try
{
double temp = std::stod(val);
row.push_back(temp);
}
catch (...)
{
std::cout << "bad input: " << val << std::endl;
}
}
std::cout << "n";
data.push_back(row);
}
for (const auto &row : data)
{
for (const auto &col : row)
std::cout << col << ", ";
std::cout << "n";
//if (data[i].size() > 4) std::cout << data[i][4] << "n";
}
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组