0

I want to convert string to float with stof but it is not working Also I was enabled c++ 11 in codeblocks but give error me that "stof was not declared in this scope" if I use of std::stof yet give error me that it is not member of std
Here is my code:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string x;
    x="23";
    float y=stof(x)+2.1;
    cout<<y;
    return 0;
}
kometen
  • 5,148
  • 4
  • 40
  • 44
Masoud
  • 21
  • 1
  • 9

2 Answers2

-1

try this:

include <sstream>
std::stringstream ss;
ss << "23";
float f;
ss >> f;
jonezq
  • 346
  • 1
  • 5
-2

You have declared y to be an integer.

By definition, integers do not have fractional or decimal parts.

When you add 2.1 it will truncate the decimal.

kmiklas
  • 12,253
  • 20
  • 61
  • 96