首页 > 解决方案 > 调用 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;
}

标签: c++

解决方案


stof 函数采用 std::string 并将其转换为浮点数,但您提供了一个无法转换为 std::string 的单个字符。

还有另一个函数 atof 更接近您的预期,但它需要一个指向您也没有的以 0 结尾的字符数组的指针。

要将单个字符转换为对应的十进制值,您可以简单地使用 values[i]-'0',因为 ASCII 码中的字符是这样排列的,例如,字母 '5' 是 5 个位置字母“0”。


推荐阅读