string to float conversion?

前端 未结 9 1860
-上瘾入骨i
-上瘾入骨i 2020-12-18 14:16

I\'m wondering what sort of algorithm could be used to take something like \"4.72\" into a float data type, equal to

float x = 4.72;
9条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-18 14:52

    From cplusplus.com: "stringstream provides an interface to manipulate strings as if they were input/output streams."

    You can initialize a stringstream with your string then read a float from the stringstream using operator>> just like you would with cin.

    Here is an example:

    #include
    #include
    #include
    using namespace std;
    
    int main() {
      string s = "4.72";
      stringstream sstrm(s);
      float x;
      sstrm >> x;
      cout << x << endl;
    }
    

提交回复
热议问题