How can I convert a double into a const char, and then convert it back into a double?
I'm wanting to convert the double to a string, to write it to a file via fputs, and then when I read the file, it will need to be converted back into a double.
I'm using Visual C++ 2010 Express Edition.
If you just want to write the double values to file, you can simply write it, without converting them into const char*. Converting them into const char* is overkill.
Just use std::ofstream as:
std::ofstream file("output.txt")'
double d = 1.989089;
file << d ; // d goes to the file!
file.close(); //done!
Since you added C++ to your tags, I suggest you use std::stringstream:
#include <sstream>
stringstream ss;
ss << myDouble;
const char* str = ss.str().c_str();
ss >> myOtherDouble;
You can use these functions to convert to and from:
template <class T>
bool convertFromStr(string &str, T *var) {
istringstream ss(str);
return (ss >> *var);
}
template <class T>
string convertToStr(T *var) {
ostringstream ss;
ss << *var;
return ss.str();
}
Example:
double d = 1.234567;
string str = convertToStr<double>(&d);
cout << str << endl;
double d2;
convertFromStr<double>(str, &d2);
cout << d2 << endl;
Use this funcition :
const char* ConvertDoubleToString(double value){
std::stringstream ss ;
ss << value;
const char* str = ss.str().c_str();
return str;
}
Related
I am trying to convert in C++ a stringstream of "1.txt" so that it is equal to a char* value of "1.txt". I need the raw char* as an argument for a function, so it can't be const char or anything else. When I run it, I get a blank output. Why, and how do I fix it?
#define SSTR(x) dynamic_cast< std::stringstream & >( (std::stringstream() << std::dec << x ) ).str()
int booknum = 1;
std::stringstream stringstream;
stringstream << SSTR(booknum) << ".txt";
std::vector<std::string> argv;
std::vector<char*> argc;
std::string arg;
std::string arg3;
while (stringstream >> arg) argv.push_back(arg);
for (auto i = argv.begin(); i != argv.end(); i++)
argc.push_back(const_cast<char*>(i->c_str()));
argc.push_back(0);
int arg4 = argc.size();
for (int i = 0; i < arg4; i++)
std::cout << &arg3[i] << std::endl;
That seems very complicated, instead of e.g.
std::ostringstream oss;
oss << booknum << ".txt";
std::string s = oss.str();
char* pString = new char[s.length() + 1];
std::copy(s.c_str(), s.c_str() + s.length() + 1, pString);
yourFunctionThatTakesCharPtr(pString);
delete[] pString;
Here's a sample conversion code:
#include <iostream>
#include <sstream>
#include <typeinfo> //it's just to print the resultant type to be sure
int main() {int booknum=1;
std::stringstream ss;
ss << booknum<<"1.txt";
char* x=new char[ss.str().length()+1];
ss >> x;
std::cout<<typeid(x).name();
return 0;}
Output:
Pc
I was looking for solutions to appending strings with other primitives and found that stringstream was the easiest solution. However, I wanted to streamline the process so I wanted to make a function to ease its use. In case you are proposing alternate methods for concatenation, i need the final result to be char*. I used a loop (i) with:
std::stringstream ss;
ss << "test" << i;
char* name = new char[ss.str().size() + 1];//allocate
strcpy(name, ss.str().c_str());//copy and put (char*)c_str in name
So the output is something link test1test2test3... This was the most reasonable solution I could muster. I was trying to put it into a function for ease of use, but am running into problems. I wanted to do something like:
char* string_to_pointer( char* dest, std::stringstream* _ss ) {
char* result = new char[_ss->str().size() + 1];
strcpy(result, _ss->str().c_str());
return result;
}
I could then do something like:
std::stringstream ss;
ss << "test" << i;
char* name = string_to_pointer( name, &ss );
I'm pretty new to c++ and this seems like the correct use syntactically, but I am running into runtime issues and would welcome solutions on how to get this in an easy to use function without resulting to Boost.
What about something like this:
#include <string>
#include <sstream>
class ToString {
std::ostringstream stream;
public:
template<typename T>
inline ToString &operator<<(const T&val) {
stream << val;
return *this;
}
inline operator std::string() const {
return stream.str();
}
};
You can use it like this:
std::string str = ToString() << "Test " << 5 << " and " << 4.2;
Use the std::stringstream::str() function to retrieve the contents of the string.
Example:
int foo = 42;
double bar = 12.67;
std::stringstream ss;
ss << "foo bar - " << foo << ' ' << bar;
std::string result = ss.str();
If you dont want to modify the string further, you can now simple call result.c_str() to acquire a const char*. However, if you really need a modifyable char* you have to copy the contents of the string to a cstring:
std::unique_ptr<char[]> cstring = new char[result.size() + 1];
strcpy(cstring.get(), result.c_str());
char* string_to_cstring ( const std::string &_ss )
Would be cleaner! Use with string_to_cstring(ss.str())
Need the returned C-String to be changeble? Because if not, just use ss.str().c_str() wherever you need it!
Or use:
char* result = new char[ss.str().size() + 1] (); // value initialized
ss.str().copy(result,std::string::npos);
I have a struct that stores the integer value as a custom string type.
typedef char OneLine[MAX_LINE + 1];
So I have some instances where I want the string that contains "12" to be converted to
C.
OneLine testString;
strcpy(testString, "12");
I'd like a way for me to convert testString to be "C"
How should I tackle this?
Thanks in advance.
You can use sscanf to convert "12" to an integer 12. Then you can use sprintf with %x format to convert integer 12 to "C"
The conversion can be done using stringstreams
#include <iostream>
#include <sstream>
#include <string>
#include <ios>
int main()
{
char const *str = "12";
std::istringstream iss( str );
int val;
if( !( iss >> val ) ) {
// handle error
}
std::ostringstream oss;
oss << std::hex << val;
std::cout << oss.str() << std::endl;
}
Or slightly less verbose way with C++11
char const *str = "12";
auto val = std::stoi( str );
std::ostringstream oss;
oss << std::hex << val;
std::cout << oss.str() << std::endl;
First, even if you were to do this manually, you shouldn't use char arrays for strings. Use std::[w]string.
Second, you can do this with std::[w][i|o]stringstream:
istringstream iss("12");
int number;
iss >> number;
ostringstream oss;
oss << hex << number;
const string& hexNumber = oss.str();
// hexNumber now contains "C"
See the example to understand
int rnd = rand() %10;
string Folder = "c://foldername";
string final_name = Folder + rnd; // here the target
/* I want the result like that (random folder name)
foldername5
foldername10
foldername3
foldername20
foldername17
*/
Use std::stringstream as:
#include <sstream> //include this
std::stringstream ss;
ss << Folder << rnd;
string final_name = ss.str();
Or you can write this just in one line:
string final_name = stringbuilder() << Folder << rnd;
All that it needs a small utility class:
struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
Using this class, you can create std::string on the fly as:
void f(const std::string & file ) {}
f(stringbuilder() << Folder << rnd);
std::string s = stringbuilder() << 25 << " is greater than " << 5 ;
In c++ you use stringstream to convert integers to strings.
int rnd = rand() %10;
string Folder = "c://foldername";
stringstream ss;
ss << Folder << rnd;
string final_name = ss.str(); // here the target
In C++ the best way to do this is to use a stringstream:
#include<sstream>
...
std::stringstream stream;
stream << "c://foldername" << rand() %10;
stream.str(); // now contains both path and number
Say this:
std::string final_name = Folder + std::to_string(rnd);
If you have an old compiler that doesn't support C++11, you can use boost::lexical_cast, or std::snprintf, or string streams.
Convert rnd (it is in integer type) to string type then do the same
string final_name = Folder + rnd;
i have a string and i need to add a number to it i.e a int. like:
string number1 = ("dfg");
int number2 = 123;
number1 += number2;
this is my code:
name = root_enter; // pull name from another string.
size_t sz;
sz = name.size(); //find the size of the string.
name.resize (sz + 5, account); // add the account number.
cout << name; //test the string.
this works... somewhat but i only get the "*name*88888" and... i don't know why.
i just need a way to add the value of a int to the end of a string
There are no in-built operators that do this. You can write your own function, overload an operator+ for a string and an int. If you use a custom function, try using a stringstream:
string addi2str(string const& instr, int v) {
stringstream s(instr);
s << v;
return s.str();
}
Use a stringstream.
#include <iostream>
#include <sstream>
using namespace std;
int main () {
int a = 30;
stringstream ss(stringstream::in | stringstream::out);
ss << "hello world";
ss << '\n';
ss << a;
cout << ss.str() << '\n';
return 0;
}
You can use string streams:
template<class T>
std::string to_string(const T& t) {
std::ostringstream ss;
ss << t;
return ss.str();
}
// usage:
std::string s("foo");
s.append(to_string(12345));
Alternatively you can use utilities like Boosts lexical_cast():
s.append(boost::lexical_cast<std::string>(12345));
Use a stringstream.
int x = 29;
std::stringstream ss;
ss << "My age is: " << x << std::endl;
std::string str = ss.str();
you can use lexecal_cast from boost, then C itoa and of course stringstream from STL