Shivam Mishra
Shivam Mishra

Reputation: 51

no matching function for call to stof

Trying to take values in string saving it in vector and stop once 'q' is given as an input. Then copying the values in other vector of float type and printing its value. But can't change string to float and it is showing error. I am using stof() to do so.

#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;
}

Upvotes: 1

Views: 1273

Answers (2)

BiOS
BiOS

Reputation: 2304

You need to do a couple of things to fix your code, keep in mind the following:

  • You are using stof() for your comparison, and stof converts a StringTOFloat, so you won't be able to provide it with a char as you are doing right now

  • It's better that you actually check if the input value is actually a number before trying to save that into your float vector

To solve the two problem above, you could actually just use the verification provided by cin.good(), which will also clean up the code quite a little. If the provided input can be stored into the float-type variable number, the while loop will add the number to the vector numbers and ask for another input. To quit the loop, just enter whatever cannot be stored into a float. Could be your letter "q" too!

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<float> numbers;
    float number;

    cin >> number;

    while (cin.good())
    {
        numbers.push_back(number);
        cin >> number;
    }

    for (auto i : numbers)
        cout << i << endl;

    return 0;
}

Upvotes: 2

gerum
gerum

Reputation: 1134

The stof function takes an std::string an converts it to a floating point number, but you gives a single char which can not be converted to an std::string.

There is another function atof which would nearer to what you expects, but it takes a pointer to an 0-terminated array of characters which you also not have.

To convert a single character to the corresponding decimal value, you can simply values[i]-'0', because the characters in the ASCII code are arranged in such a way that the letter '5', for example, is 5 positions from the letter '0' away.

Upvotes: 1

Related Questions