How can I convert a number into text and output it to the console using C ++? For example:
float x = 0.05f; char *str; //str = x
How can I convert a number into text and output it to the console using C ++? For example:
float x = 0.05f; char *str; //str = x
Option 1.
#include <stdio.h> printf("Number is %f\n", x);
Option 2.
#include <iostream> std::cout << "Number is " << std::scientific << x << std::endl;
Here is to use C to convert C ++ methods like atoi, sprintf, etc. may be fraught with consequences. Here is a purely C ++ option based on streams, moreover a universal one. You can convert at least integer types, even floating point.
`
#include <string> #include <sstream> template <typename T> std::string toString(T val) { std::ostringstream oss; oss<< val; return oss.str(); } template<typename T> T fromString(const std::string& s) { std::istringstream iss(s); T res; iss >> res; return res; }
Used as follows
std::string str; int iVal; float fVal; str = toString(iVal); str = tiString(fVal); iVal = fromString<int>(str); fVal = fromString<float>(str);
I took an example from here. Algorithms for converting a string to a number and back (cyberguru)
solution in c ++ 11
http://www.cplusplus.com/reference/string/to_string/
#include <string> int x = 10; std::string y = std::to_string(x);
Use the sprintf function from stdio.h:
float x = 0.05f; char str[20]; sprintf(str, "%f", x);//или любой другой формат, как это делается в printf() std::cout << str << std::endl;
strstream s; float x = 0.05f; s << x; //преобразование в строку
upd: you can still use stringstream
strstream
deprecated; strstream
should be used stringstream
. - Abyx pm #include "stdafx.h" #include <iostream> #include <sstream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { float a = 33.5; int b = 50; char str[50]; _TOSTRING(str, "%f", a); cout << str << endl; _TOSTRING(str, "%d", b); cout << b; return 0; }
string flts (long x) { string s; char c; while(x) { c=(x%10)+'0'; s=c+s; x=x/10; } return s; }
Source: https://ru.stackoverflow.com/questions/23983/
All Articles