在 c++ 中将字符串转换为双精度
Converting string to double in c++
我做了一个函数,它接收一行和一个分隔符,分隔线并返回浮点数向量(如java中的split
函数)。这是函数:
vector<float> extractNumbers(string line, char delimiter) {
vector<float> a;
float f;
string forNow = "";
for (unsigned int i = 0; i < line.size(); i++) {
if (line.at(i) == delimeter) {
f = ::atof(forNow.c_str());
cout << ::atof(forNow.c_str()) << endl;
a.push_back(f);
forNow = "";
} else {
forNow += line.at(i);
}
}
f = ::atof(forNow.c_str());
cout << f << endl;
a.push_back(f);
return a;
}
这是我正在尝试的文本文件:
3 3
1 1 1
1 2 1
1 1 1
我调用此函数:vector<float> floatLine = extractNumbers(line, ' ');
当我尝试打印forNow
参数时,我收到的数字就像文本中一样,但是当我打印f
或::atof(forNow.c_str())
时,我收到 0 而不是第一行的前 3。有什么想法吗?
只是如果您不知道与文件交互的这种便捷方式。您可以像这样使用它们:
float a, b;
float c, d, e;
float f, g, h;
fstream file("data.dat", ios::in);
if (file) {
file >> a >> b;
file >> c >> d >> e;
file >> f >> g >> h;
file.close();
}
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何从字符串转换为双精度*
- C++如何将字符串逐行转换为双精度
- 如何防止双精度值到整数的隐式转换
- 如果存在从"双精度"到"T"的转换,则禁用构造函数
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将双精度值转换为 char 变量时字符串流如何工作
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 在 c++ 中从双精度转换为字符串
- 如何在C++中将无符号字符缓冲区转换为双精度?
- 从字符串转换为双精度和整数 - C++
- 如何使用按位运算将随机uint64_t转换为范围 (0, 1) 的随机双精度
- 使用 sprintf 和 %g 将双精度转换为字符串的意外结果
- 表达式中应用的转换(双精度为整数)
- 无法转换双精度 - 新运算符
- C++类型转换双精度