c++ - 调用 stof 没有匹配的函数
问题描述
尝试将字符串中的值保存在向量中,并在将“q”作为输入时停止。然后复制其他浮点类型向量中的值并打印其值。但不能将字符串更改为浮动,并且显示错误。我正在使用 stof() 这样做。
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main(){
string addDigit;
vector<string> values;
vector<float> number;
while (cin >> addDigit) {
if (addDigit == 'q') {
break;
}
else {
values.push_back(addDigit);
}
}
int size=values.size();
for (int i = 0; i < size; ++i) {
float num=std::stof(values[i]);
number.push_back(num);
}
for (int i = 0; i < size; ++i) {
std::cout<<number[i];
}
cout << "\n" << endl;
return 0;
}
解决方案
stof 函数采用 std::string 并将其转换为浮点数,但您提供了一个无法转换为 std::string 的单个字符。
还有另一个函数 atof 更接近您的预期,但它需要一个指向您也没有的以 0 结尾的字符数组的指针。
要将单个字符转换为对应的十进制值,您可以简单地使用 values[i]-'0',因为 ASCII 码中的字符是这样排列的,例如,字母 '5' 是 5 个位置字母“0”。
推荐阅读
- angular - 在 Chrome 开发工具中观看的表达式未显示值
- hdl - 有符号二进制数乘法-芯片HDL代码
- java - 无限while循环,而AsyncTask没有完成
- c++ - 在这里使用删除运算符是否正确我很困惑
- sql-server - 如何使用 3 部分命名约定访问 SQL Server 系统函数,如 CAST、CONVERT
- python-3.x - Gurobi - addConstr:不支持的操作数类型 -:'bool' 和 'NoneType'
- c# - 从组织存储库获取 NuGet 包
- json - Swift MVVM 如何实现 Array 来建模
- excel - 设置单元格值的“错误数据类型”错误
- python - Time Series Prediction with Keras - Error in Model Values