Char and Float (Simple)
quote:Original post by brain21quote:
Don''t use itoa.
yeah, don''t use itoa....or printf, cout, cin, include, define, main() and everything else.
Let him use what he/she wants to use ok. Unless you have a reason....in which you can include with your post.
Everyone should know the reason already: itoa isn''t standard.
Everything else you mention is part of the language standard or the standard library... assuming you mean "int main()" and not "void main()".
quote:Original post by Aface
Jingo''s method is safest.
Also it''s the only method posted in this thread so far that actually works.
template<class T>std::string toString(const T& thing) { std::ostringstream ss; ss << thing; return ss.str();}std::string f = toString(3.142f);std::string d = toString(3.1415926535897932);std::string n = toString(153);std::string c = toString(std::complex<double>(1.7, 6.5));
edit: changed to ostringstream
[edited by - petewood on February 11, 2004 8:30:14 AM]
Pete,
I have found that there is a default number of significant numbers that the stringstream will accept (determined by the type being streamed onto it). Is there a simple way to have a variable number of significant figures (ie that change the number streamed to the number contained in the float?)
Alex
I have found that there is a default number of significant numbers that the stringstream will accept (determined by the type being streamed onto it). Is there a simple way to have a variable number of significant figures (ie that change the number streamed to the number contained in the float?)
Alex
Just set the std::ios_base::fixed flag and use the setprecision manipulator to change the number of decimal places, something a bit like this:
You can set the precision by changing the 3rd parameter passed to append
[edited by - Jingo on February 12, 2004 5:41:59 AM]
#include<sstream>#include<string>#include<iostream>#include<iomanip>#include<stdexcept>#include<cstddef>template<typename T, typename chartype, class traits, class alloc>std::basic_string<chartype, traits, alloc>& append(const T& num, std::basic_string<chartype, traits, alloc>& str, std::size_t precision_param = 0){ std::basic_ostringstream<chartype, traits, alloc> o; o << std::fixed << std::setprecision(precision_param); if(!(o << num)) throw std::logic_error("invalid conversion"); str+=o.str(); return str;}int main(){ std::string s1, s2; append<float>(10.213123, s1, 2); append<float>(10.213123, s2, 10); std::cout << s1 << std::endl << s2 << std::flush;}
You can set the precision by changing the 3rd parameter passed to append
[edited by - Jingo on February 12, 2004 5:41:59 AM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement