How to convert a double variable into a char array? - c++

I'm working on a project for school, and we just found out that outtextxy() (a function from graphics.h, which we must use) requires as the text parameter a char array.
Here is its declaration: void outtextxy (int x, int y, char *textstring)
The issue is that we need to print out a number of type double, including the decimal point. I have previously tried making it work using knowledge from other similar questions, but none has worked.
Here are is my latest attempt, which resulted in a Segmentation Fault:
char *DoubleToString(long double x)
{
char s[256]="\000";
std::ostringstream strs;
strs << x;
string ss = strs.str();
for(int i=0; i < ss.length(); i++)
s[i] = ss[i];
return s;
}
NOTE: I am still somewhat new to programming and I don't exactly know what ostringstream and the bitshift-looking operation are doing, but I tried to copy-paste that part in hopes of it working.

... requires as the text parameter a char array.
Ok, then use a std::string:
std::string DoubleToString(long double x)
{
std::ostringstream strs;
strs << x;
return strs.str();
}
If you need the underlying character array use the strings data() method. It does return a pointer to the first element of the strings character array. For example:
std::string s = DoubleToString(3.141);
function_that_needs_pointer_to_char( s.data() );
Note that before C++17 data returned a const char* (and since C++11 the character array is null-terminated, as one would expect ;).

I know it is undefined behaviour, but it works. And I only need to pass the returned char* to outtextxy(), and not manipulate it later on, since I have the double variable stored in an object.
char *DoubleToString(long double x)
{
char s[256]="\000";
std::ostringstream strs;
strs << x;
string sd = strs.str();
strcpy(s, sd.data());
return s;
}

Related

Why casting a quoted string to "string &" causes a crash?

Please note that's just a curious question, I don't need a problem solution!
I have a method that takes in a string reference (string &some_string) and only reads from referenced string. Writing some code I forgot that it needs a reference and passed a quoted string (not a variable, just like "something") and IDE suggested casting it to string reference, as it won't compile. I didn't give it a thought and applied the suggestion (now passing (string &) "something"). And my program crashed as it reached this piece of code. So, why exactly would it cause a crash, compiling without even a warning (g++, c++11)? I don't really understand it since I'm only reading from this string.
Example:
#include <string>
#include <iostream>
using namespace std;
class CharSet
{
private:
const string basis = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const int N = 26;
string array; // string containing all element of the set
int length;
bool add_element(char chr) // Add an element (as char) if not already. Returns true if added, false if not.
{
bool b = false;
if (!in_set(chr) && basis.find(chr) != string::npos) {
array += chr;
length++;
b = true;
}
return b;
}
bool in_set(char chr) const // Checks whether an element (as char) is in set. Returns corresponding bool value.
{
bool b = false;
if (array.find(chr) != string::npos) b = true;
return b;
}
public:
explicit CharSet(string& str) // str - string of possible elements
{
array = "";
length = 0;
int len = (int) str.length();
for (int i = 0; i < len; i++)
add_element(str[i]);
if (str.length() != length)
cout << "\nSome mistakes corrected. Elements read: " << array << endl;
}
};
int main()
{
CharSet A((string &)"AKEPTYUMRX");
getchar();
return 0;
}
A cast like this
(string)"a string literal"
constructs a new std::string by passing "a string literal" as an argument to its constructor. It is equivalent to static_cast<std::string>("a string literal"). It is completely valid, even though C-style casts in C++ are a bad idea in general.
On the other hand, a cast like this
(string&)"a string literal"
constructs a reference to an std::string object that resides at the same location as the string literal. Since there is no such object at that location, using this reference results in undefined behaviour (often expressed as a crash). This cast is equivalent to reinterpret_cast<std::string&>("a string literal"). You might know that reinterpret_cast is dangerous and should be avoided as much as possible. With reinterpret_cast, the compiler trusts the programmer nearly totally, which is not really a wise thing to do, but such is the C++ way.
For your function to be able to accept a string literal, it should have a const std::string& parameter, or perhaps better, if you are using C++17, an std::string_view.

How to convert string to char* using stringstream?

I have a function like this:
template <typename T>
void parse_to_T(const std::string& str, T* result) {
std::stringstream ss;
ss << str;
ss >> *result;
}
this function is mean to convert the string to the specified type.
it is work to parse the string to int, float or char.
parse_to_T<int>(...);
parse_to_T<float>(...);
parse_to_T<char>(...);
but when meet char*, segment fault ...
I use the function like this:
int int_val;
string m = "1";
parse_to_T<int>(m, &int_val); // works
char* str_val = NULL;
parse_to_T<char*>(m, &str_val); // segmentfault
How to imply this function to make it work?
(convert the string to specified type like int, double, char, char*)?
Hey, I don't know how to explain my use case, but I will try:
To simple, the question is, given a file, for each line, data may have these types :
int
float
char
char*
an array T[num] (T is int, float, char or char*, or any build_in type.)
imple a parse function to parse this file.
and this problem is an exam ...
thanks and I found the error now.
char* str_val = NULL;
parse_to_T<char*>(m, &str_val); // segmentfault;
char* str_val;
parse_to_T<char*>(m, &str_val); // segmentfault;
char* str_val = new char[256];
parse_to_T<char*>(m, &str_val); // works !!
then the error is I didn't allocate memory to the ptr...
This segfault is because stringstream does not allocate memory to hold the result of the operation when extracting values into a char* array. It tries to put the values into the memory pointed at by the lhs operand. You must allocate memory yourself.
Here is a simple example:
#include <string>
#include <sstream>
#include <iostream>
template <typename T>
void parse_to_T(const std::string& str, T* result) {
std::stringstream ss;
ss << str;
std::cout << ss.str() << std::endl;
ss >> *result;
std::cout << *result << std::endl;
}
int main() {
char* buffer = new char[256];
/* Don't do this in real code. If the input is larger than
the size of the buffer it will end very, very badly.
always have a way of allocating the correct amount
of memory.
*/
int int_val;
std::string m = "1";
parse_to_T<int>(m, &int_val);
char* str_val = NULL;
parse_to_T<char*>(m, &buffer);
delete[] buffer;
return 0;
}
You could include a template specialization for the char* datatype that does the allocation based on the amount of data in the stream (calling stringstream.str().size() should work) but the user would have to free the returned memory.
First, your destination variable str_val has no allocated memory, so it is normal you have a segmentation fault.
On the other hand, it would be better if you use std::string instead. If you need the raw pointer const char* then you can use std::string::c_str for so. If you have to modify it then just create a copy.

Automatically Concatenate Strings and Int C++

In Lua (apologise, I like working with it the best), the conversion between int and string is done automatically, so
"hi"..2
would result as
"hi2"
In C++ (cause I can't seem to get the default C++11 stoi() and to_string() methods to work) I defined these for myself:
int stoi(string str) {
char* ptr;
strtol(str.c_str(), &ptr, 10);
}
string to_string(int i) {
char* buf;
sprintf(buf, "%d", i);
return buf;
}
which are basically how the default ones are defined anyways.
Then I did this:
string operator+ (string& stuff, int why) {
stuff.append(to_string(why));
}
I tried it on the following code:
void print(string str) {
cout << str << endl;
}
int main() {
cout << stoi("1") + 2 << endl;
print("die" + 1);
return 0;
}
And it outputs
3
ie
Why is this so, and how can I fix it?
EDIT:
Here's what the code looks like now:
using namespace std;
string to_string(int i) {
char* buf;
sprintf(buf, "%d", i);
return buf;
}
string operator+ (string stuff, int why) {
stuff.append(to_string(why));
return stuff;
}
int main() {
cout << string("die") + 2 << endl;
return 0;
}
And it just keeps giving me stackdumps.
Replace print("die" + 1); with cout << std::string("die") + 1;
print() doesn't know what to do with strings. Use std::cout. "die" is a char*, +1 will increment the pointer.
std::string to_string(int i) {
char buf[(sizeof(int)*CHAR_BIT+2)/3+3];
sprintf(buf, "%d", i);
return buf;
}
You need to make an actual buffer to print to. The math is a quick over-estimate of big the largest decimal int is in characters; 3 bits can fit in 1 decimal character, plus null, plus negation, plus rounding, plus 1 for good measure. Hopefully I did not err: do some testing.
Also use snprintf instead of sprintf while you are at it: buffer overflows are not to be toyed with.
The next problem is that "hello" is not a std::string, It is a char const[6] -- an array of 6 char. It can be converted tomstd::string, but +1 will instead convert it to a pointer to the first character, then +1 it to the 2nd character.
Cast it to std::string before.
Finally, it is ambiguous in the standard (really) of pverloading an operator on std::string + int is legal. It is definitely poor practice, as you cannot do it in std legally, and you should overload operators in the type's namespace (so ADL works): these two conflict. On top of that, if std in the future adds such a + your code starts behaving strangely. On top of that, operators are part of a class's interface, and modifying the interface of a class you do not 'own' is rude and a bad habit.
Write your own string class that owns a std::string rather. Or a string view.
Finally, consider telling your compiler to use c++11, you probably just need to pass a flag to it like -std=c++11.
std::string s1("h1");
std::string s2("2");
s1 += s2;
If you are using C++11 compatible compiler you can convert int to string like this:
int i = 2;
std::string s = std::to_string(i);
If you are using Boost library:
#include <boost/lexical_cast.hpp>
int i = 2;
std::string s = boost::lexical_cast<std::string>(i);
Please do not use raw char pointers in C++ for strings.
overloading the operator+ on other than your own types it at best dangerous.
Just use std::to_string in conjunction with operator+ or +=, e.g.
std::string x = "hi";
x += std::to_string(2);
C++14 introduces a user-defined literal that takes a string literal (conversions are applied to make this a pointer) and returns a std::string. In C++11, you can just write your own (this is taken from libstdc++):
inline std::string
operator""_s(const char* str, size_t len)
{
return std::string{str, len};
}
(Note: UDLs without a preceding underscore are reserved names)
And you can use it like this:
// Assumes operator+ is overloaded
print("die"_s + 1);
Demo
"die" is not a std::string. It's a string literal.
Thus when you add 1 to the string literal, it decays to a const char* and the + 1 simply increments that pointer — to next char, 'i'.
Then you call print with the incremented pointer, which causes a std::string to be constructed using that pointer. Since it pointed to the 'i' character, to constructed string is initialized to "ie".
You must first make a std::string out of your string literal to make it call your operator+:
std::cout << std::string("die") + 1;
And then make a few fixes to your operator+:
string operator+ (string stuff, int why) {
return stuff.append(to_string(why));
}
Now it works.

How to convert int and std::string to char*? [duplicate]

This question already has answers here:
Easiest way to convert int to string in C++
(30 answers)
Closed 8 years ago.
How to convert int and std::string to char* ?
I'm trying to do this :
int a = 1;
std::string b = "str";
char* x = a + b;
I don't want something like this:
std::stringstream ss;
std::string str2char;
ss << a;
str2char = ss.str() + "str";
std::vector<char> writable(str2char.size() + 1);
std::copy(str2char.begin(), str2char.end(), writable.begin());
x = &writable[0];
How to deal with this, please.
One way would be to use a string stream (include <sstream>), output data of various types into it, and then grab the output as a string or as a const char*, like this:
std::stringstream ss;
int a = 1;
std::string b = "str";
ss << a << b;
std::string res(ss.str());
const char *x = res.c_str();
Demo on ideone.
If you need to convert to char*, not to const char*, make a copy of c_str instead - replace the last line as follows:
char *x = new char[res.size()+1];
strcpy(x, res.c_str());
// Use x here, then...
delete[] x;
Finally, you can use vector instead of a string to get a writable pointer without the need to delete. Note that this approach does not let you return your char* from a function, because its data would be tied to the scope of the vector with its characters. Here is a demo of this approach.
If you are using C++11, std::to_string() is a good option:
int a = 1;
std::string b = "str";
std::string one = std::to_string(a);
std::string one_plus_b = (one + b);
const char * x = one_plus_b.c_str();
And as it was pointed out by other answers, 'x' can only be used inside the local scope.
int and std::string to char*?
Here are a couple one-liners:
char* p = strdup((std::to_string(a) + b).c_str());
...use p...
free(p);
...or, if your system provides it (I don't think it's in the C++ Standard itself)...
char* p = asprintf("%d%s", a, b.c_str());
...use p...
free(p);
Note that these are C library functions, and the memory allocation is malloc/realloc/free-family, which can not be mixed with new/delete (which means the pointer shouldn't be wrapped in a Standard smart pointer, though of course a free-specific or generic scope guard could be used).

C++ const char* To const char* const

I am currently writing an assignment for my class that is supposed to act as a very basic shell. I am nearly finished, but I am running into an issue with execvp and my character array of parameters. Here is a light snippet of my code.
//Split the left content args
istringstream iss(left);
while(getline(iss, s, ' ')){
v.push_back(s);
}
//Get the split string and put it into array
const char* cmd_left[v.size()+1];
for(unsigned int i = 0; i < v.size(); i++){
cmd_left[i] = v.at(i).c_str();
}
cmd_left[v.size()] = 0;
v.clear();
And this is utilized by...
execvp(cmd_left[0], cmd_left);
My error is
assign3.cxx:96:34: error: invalid conversion from ‘const char**’ to ‘char* const*’ [-fpermissive]
I understand that the problem is that my character array isn't full of constant data, so I need to essentially go from const char* to const char* const. I read something about const_cast, but I wasn't sure if that is what I need to be doing.
If you would be so kind, could you help me get my array of character arrays to be properly accepted by that function? If you need me to post more of my code, let me know.
Thanks
The problem is you cannot pass const variable to function expecting non-const argument.
other word, const char * is a subset of char *.
remove the const
/*const*/ char* cmd_left[v.size()+1];
add const_cast here
cmd_left[i] = const_cast<char *>( v.at(i).c_str() );
other parts of your code look suspicious, but this will make it compile
Without any const_cast:
istringstream iss(left);
while(getline(iss, s, ' ')){
v.push_back(s);
}
//assuming v is not empty! which you were already
string command = v[0]; //store the command in a separate variable (this makes a copy of the string)
char* cmd_left[v.size()+1]; //not a (const char)*
for(unsigned int i = 0; i < v.size(); i++){
cmd_left[i] = new char[v[i].size()+1];
strcpy(cmd_left[i], v[i].c_str()); //copy contents of each string onto a new buffer
}
cmd_left[v.size()] = NULL;
v.clear(); //if you really want to; not necessary from the code you posted
//...
execvp(command.c_str(), cmd_left);
It is not easy, sometimes not possible to create a const dynamic array of elements because all the elements have to declared within the initializer {}.
But luckily you could tell the compiler that the array you are passing is going to be const at least for the certain duration. You could do the following this would yield
&((char* const) (const_cast<char*>(cmd_left[0]) ))
The const_cast inside would remove the const-ness of the array of characters std::string is owning. So, it is quite possible that function might change the contents of array of characters behind the back of std::string. When behaviour of functions taking such argument is known then this might be ok.
If you want to create a const array of char* without resorting to const_cast or managing memory using new/delete, you could use std::vector > instead of vector of strings.
istringstream iss(left);
while(getline(iss, s, ' ')){
v.push_back(std::vector<char>(s.length()+1));
strcpy(&v.back().front(),s.c_str());
}
//Get the split string and put it into array
char* cmd_left[v.size()+1];
for(unsigned int i = 0; i < v.size(); i++){
cmd_left[i] = &v.at(i).front();
}
cmd_left[v.size()] = 0;
v.clear();
execvp(cmd_left[0], &((char* const)cmd_left[0]));
Hope this helps.