Convert doubles to char*/string in C++ - c++

I am pretty sure this is no hard task, but I don’t get what causes the problems, and I would like to really understand this, since I often have some pointer/array/cast-related problems:
I store the bounding box values in a double*
// this is the calss-variable
double *_boundingBox;
// this is where I put some data in it
double boundingBox[6];
boundingBox[0] =
.
.
.
boundingBox[6] = ....;
// set pointer to boundingbox
_boundingBox = &boundingBox;
and in an other class I use this
double* getBoundingBoxInfo()
{
return _boundingBox;
}
to get my bounding box-data, which I would like to input in a QLabel as QString
double boundingBox[6];
boundingBox[0] = *_drawer->getBoundingBoxInfo();
std::string stringX = "x start: " << boundingBox[0] << "\tx end: " << boundingBox[3];
QLabel *labelX = new QLabel(QString(stringX.c_str()));
The current compile-error is
error: invalid operands of types ‘const char [10]’ and ‘double’ to binary ‘operator<<’
Could someone please tell me how this should work? Am I using double*, double[] and string the way they are supposed to be used?

You cannot stream data into a std::string as-is. A solution is to use std::ostringstream:
std::ostringstream out;
out << "x start: " << boundingBox[0] << "\tx end: " << boundingBox[3];
std::string stringX = out.str();

The compilation error you're getting is for "x start: " << boundingBox[0].
The type of "x start: " is const char*, and the type of boundingBox[0] is double.
But there is no definition for operator<<(const char*,double).
You can get this to work by using an ostringstream object:
ostringstream oss;
oss << "x start: " << boundingBox[0] << "\tx end: " << boundingBox[3];
std::string stringX = oss.str();
As a side-note, when you set _boundingBox = &boundingBox, you don't need the &, because boundingBox is an array, so in essence, boundingBox == &boundingBox.
The reason for this (in case you were wondering) is that arrays don't have an l-value, and you cannot change the value of an array (for example, you cannot do boundingBox = ...).

QString provides everything http://qt-project.org/doc/qt-4.8/qstring.html#arg-20
so just use
QString("some text for double value: %1").arg(yourdouble, <additional parameters>)
and in your case:
... new QLabel(QString("x start: %1\tx end: %2").arg(boundingBox[0]).arg(boundingBox[3]));

Related

Convert double and vertex handle into a string in c++

I want to convert a vertex handle(vit) and double value to string and write it into a file.I thought this works.
string buffer = vit->point() + " " +z_co[vit->id] +"\n";
z_co:is a vector.(double)
But,it is throwing error.So,How could I do this?
You can't append a double to string like that.
Instead use e.g. std::ostringstream:
std::ostringstream os;
os << vit->point() << " " << z_co[vit->id] << '\n';
std::string buffer = os.str();

Convert double point coordinates into string

string Point::ToString(const Point& pt)
{
std::stringstream buffX; //"Incomplete type is not allowed"????
buffX << pt.GetX(); // no operator "<<" matches these operands????
std::stringstream buffY;
buffY << pt.GetY();
string temp = "Point(" + buffX + ", " + buffY + ")"; //???....how to combine a couple of strings into one?..
return temp.str();
}
I followed the code from similar questions, but the system says "Incomplete type is not allowed"---red line under buffX
also red line under "<<" says that---- no operator "<<" matches these operands
really don't know why..
Thank you!
You need to #include <sstream> to use std::ostringstream.
Then:
std::string Point::ToString(const Point& pt)
{
std::ostringstream temp;
temp << "Point(" << pt.GetX() << ", " << pt.GetY() << ")";
return temp.str();
}
It's not clear why you're passing in a Point, since this is a member of that class. Perhaps cleaner would be:
std::string Point::ToString() const
{
std::ostringstream temp;
temp << "Point(" << GetX() << ", " << GetY() << ")";
return temp.str();
}
This, perhaps incorrectly, assumes that GetX() and GetY() return some kind of numeric type (int, float, double, ...). If this is not the case, you may want to either change them (the principle of least astonishment) or access the underlying data members of the class directly.
If you're struggling with this kind of compiler error, I strongly recommend you get yourself a good C++ book.

How to form a C++ string from concatenations of string literals?

I would like concatenate string literals and ints, like this:
string message("That value should be between " + MIN_VALUE + " and " + MAX_VALUE);
But that gives me this error:
error: invalid operands of types ‘const char*’ and ‘const char [6]’ to binary ‘operator+’|
What is the correct way to do that? I could split that in 2 string declarations (each concatenating a string literal and a int), but that's ugly. I've also tried << operator.
Thanks
You should probably use stringstream for this.
#include <sstream>
std::stringstream s;
s << "This value shoud be between " << MIN_VALUE << " and " << MAX_VALUE;
message = s.str();
The c++ way to do this is to use a stringstream then you can use the << operator. It will give you a more consistent code feel
There are many ways to do this, but my favourite is:
string message(string("That value should be between ") + MIN_VALUE + " and " + MAX_VALUE);
That extra string() around the first literal makes all the difference in the world because there is an overloaded string::operator+(const char*) which returns a string, and operator+ has left-to-right associativity, so the whole thing is turned into a chain of operator+ calls.
#include <sstream>
#include <string>
template <typename T>
std::string Str( const T & t ) {
std::ostringstream os;
os << t;
return os.str();
}
std::string message = "That value should be between " + Str( MIN_VALUE )
+ " and " + Str( MAX_VALUE );
You probably want to use a stringstream like this:
std::stringstream msgstream;
msgstream << "That value should be between " << MIN_VALUE << " and " << MAX_VALUE;
std::string message(msgstream.c_str());

Concatenation operator in C++?

I have an application in which I need to combine strings within a variable like so:
int int_arr[4];
int_arr[1] = 123;
int_arr[2] = 456;
int_arr[3] = 789;
int_arr[4] = 10;
std::string _string = "Text " + int_arr[1] + " Text " + int_arr[2] + " Text " + int_arr[3] + " Text " + int_arr[4];
It gives me the compile error
Error C2210: '+' Operator cannot add pointers" on the second string of the expression.
As far as I can tell I am combining string literals and integers, not pointers.
Is there another concatenation operator that I should be using? Or is the expression just completely wrong and should figure out another way to implement this?
BTW I am using Visual Studio 2010
Neither C nor C++ allow concatenation of const char * and int. Even C++'s std::string, doesn't concatenate integers. Use streams instead:
std::stringstream ss;
ss << "Text " << int_arr[1] << " Text " << int_arr[2] << " Text " << int_arr[3] << " Text " << int_arr[4];
std::string _string = ss.str();
You can do this in Java since it uses the toString() method automatically on each part.
If you want to do it the same way in C++, you'll have to explicitly convert those integer to strings in order for this to work.
Something like:
#include <iostream>
#include <sstream>
std::string intToStr (int i) {
std::ostringstream s;
s << i;
return s.str();
}
int main (void) {
int var = 7;
std::string s = "Var is '" + intToStr(var) + "'";
std::cout << s << std::endl;
return 0;
}
Of course, you can just use:
std::ostringstream os;
os << "Var is '" << var << "'";
std::string s = os.str();
which is a lot easier.
A string literal becomes a pointer in this context. Not a std::string. (Well, to be pedantically correct, string literals are character arrays, but the name of an array has an implicit conversion to a pointer. One predefined form of the + operator takes a pointer left-argument and an integral right argument, which is the best match, so the implicit conversion takes place here. No user-defined conversion can ever take precedence over this built-in conversion, according to the C++ overloading rules.).
You should study a good C++ book, we have a list here on SO.
A string literal is an expression returning a pointer const char*.
std::stringstream _string_stream;
_string_stream << "Text " << int_arr[1] << " Text " << int_arr[2] << " Text " << int_arr[3] << " Text " << int_arr[4];
std::string _string = _string_stream.str();

Comparing Character Literal to Std::String in C++

I would like to compare a character literal with the first element of string, to check for comments in a file. Why use a char? I want to make this into a function, which accepts a character var for the comment. I don't want to allow a string because I want to limit it to a single character in length.
With that in mind I assumed the easy way to go would be to address the character and pass it to the std::string's compare function. However this is giving me unintended results.
My code is as follows:
#include <string>
#include <iostream>
int main ( int argc, char *argv[] )
{
std::string my_string = "bob";
char my_char1 = 'a';
char my_char2 = 'b';
std::cout << "STRING : " << my_string.substr(0,1) << std::endl
<< "CHAR : " << my_char1 << std::endl;
if (my_string.substr(0,1).compare(&my_char1)==0)
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
std::cout << "STRING : " << my_string.substr(0,1) << std::endl
<< "CHAR : " << my_char2 << std::endl;
if (my_string.substr(0,1).compare(&my_char2)==0)
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
std::cout << "STRING : " << my_string << std::endl
<< "STRING 2 : " << "bob" << std::endl;
if (my_string.compare("bob")==0)
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
}
Gives me...
STRING : b
CHAR : a
NOPE...
STRING : b
CHAR : b
NOPE...
STRING : bob
STRING 2 : bob
WOW!
Why does the function think the sub-string and character aren't the same. What's the shortest way to properly compare chars and std::string vars?
(a short rant to avoid reclassification of my question.... feel free to skip)
When I say shortest I mean that out of a desire for coding eloquence. Please note, this is NOT a homework question. I am a chemical engineering Ph.D candidate and am coding as part of independent research. One of my last questions was reclassified as "homework" by user msw (who also made a snide remark) when I asked about efficiency, which I considered on the border of abuse. My code may or may not be reused by others, but I'm trying to make it easy to read and maintainable. I also have a bizarre desire to make my code as efficient as possible where possible. Hence the questions on efficiency and eloquence.
Doing this:
if (my_string.substr(0,1).compare(&my_char2)==0)
Won't work because you're "tricking" the string into thinking it's getting a pointer to a null-terminated C-string. This will have weird effects up to and including crashing your program. Instead, just use normal equality to compare the first character of the string with my_char:
if (my_string[0] == my_char)
// do stuff
Why not just use the indexing operator on your string? It will return a char type.
if (my_string[0] == my_char1)
You can use the operator[] of string to compare it to a single char
// string::operator[]
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str ("Test string");
int i; char c = 't';
for (i=0; i < str.length(); i++)
{
if (c == str[i]) {
std::cout << "Equal at position i = " << i << std::endl;
}
}
return 0;
}
The behaviour of the first two calls to compare is entirely dependent on what random memory contents follows the address of each char. You are calling basic_string::compare(const char*) and the param here is assumed to be a C-String (null-terminated), not a single char. The compare() call will compare your desired char, followed by everything in memory after that char up to the next 0x00 byte, with the std::string in hand.
Otoh the << operator does have a proper overload for char input so your output does not reflect what you are actually comparing here.
Convert the decls of and b to be const char[] a = "a"; and you will get what you want to happen.
Pretty standard, strings in c++ are null-terminated; characters are not. So by using the standard compare method you're really checking if "b\0" == 'b'.
I used this and got the desired output:
if (my_string.substr(0,1).compare( 0, 1, &my_char2, 1)==0 )
std::cout << "WOW!" << std::endl;
else
std::cout << "NOPE..." << std::endl;
What this is saying is start at position 0 of the substring, use a length of 1, and compare it to my character reference with a length of 1. Reference