C ++ Double string conversion

I have been trying to find a solution for this all day! You can designate this as a repeated message, but what I'm really looking for is a solution without using accelerated lexical casting . A traditional C ++ way to do this would be great. I tried this code, but it returns a set of numbers and letters a stool.

string line; double lineconverted; istringstream buffer(line); lineconverted; buffer >> lineconverted; 

And I tried this, but it ALWAYS returns 0.

 stringstream convert(line); if ( !(convert >> lineconverted) ) { lineconverted = 0; } 

Thank you in advance:)

EDIT: for the first solution I used (gibberish) .. Here is a snapshot enter image description here

+4
source share
3 answers
 #include <sstream> int main(int argc, char *argv[]) { double f = 0.0; std::stringstream ss; std::string s = "3.1415"; ss << s; ss >> f; cout << f; } 

It’s good that this solution also works for others, for example, for ints, etc.

If you want to reuse the same buffer, you must make ss.clear between them.

There is also a shorter solution in which you can initialize the value to a string stream and simultaneously clear it to a double:

 #include <sstream> int main(int argc, char *argv[]){ stringstream("3.1415")>>f ; } 
+12
source

With C ++ 11, you can use std::stod :

 string line; double lineconverted; try { lineconverted = std::stod(line); } catch(std::invalid_argument) { // can't convert } 

But the solution with std::stringstream also true:

 #include <sstream> #include <string> #include <iostream> int main() { std::string str; std::cin >> str; std::istringstream iss(str); double d = 0; iss >> d; std::cout << d << std::endl; return 0; } 
+4
source

If you want to save (e.g. vector) all line doublings

 #include <iostream> #include <vector> #include <iterator> int main() { std::istream_iterator<double> in(std::cin); std::istream_iterator<double> eof; std::vector<double> m(in,eof); //print std::copy(m.begin(),m.end(),std::ostream_iterator<double>(std::cout,"\n")); } 
0
source

Source: https://habr.com/ru/post/1482696/


All Articles