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();
Related
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I've been trying to append an integer to a string, and I've tried several solutions here, including:
std::stringstream ss;
ss << gvHours << "\'" << gvMinutes << "\"" << gvSeconds << ":" << gvTicks;
std::string output(ss.str());
return output.c_str();
and
std::stringstream ss;
std::string output = "";
ss << gvHours << "\'" << gvMinutes << "\"" << gvSeconds << ":" << gvTicks;
output = ss.str();
return output.c_str();
The first one gives me an empty string, and the second gives me an unreadable character that Notepad++ displays as "SOH" in a black box. Does anyone have any idea what I'm doing wrong?
Yes, this part
return output.c_str();
is broken.
When you take c_str() from a std::string, you are just getting a c-style pointer to the contents of that string. But you are not getting ownership of the data underlying that string. As soon as you return from the function, that stringstream and string are destroyed (as they are local variables) and the c_str() is a dangling pointer. So the whole thing is undefined behavior.
I fixed it. Here's the code I got that works:
std::stringstream ss;
std::string output;
ss << gvHours << "\'" << gvMinutes << "\"" << gvSeconds << ":" << gvTicks;
output = ss.str();
return output;
And in the function where it was needed:
fprintf(gvLog, ">: %s\n", timeString().c_str());
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]));
Sorry for my English.
I need to convert double value to CString, because i need to do AfxMessageBox(double_value);
I find this:
std::ostringstream ost;
ost << double_value;
std::cout << "As string: " << ost.str() << std::endl;
//AfxMessageBox(ost.str()); - Does not work.
How i can do this?
AfxMessageBox expects a CString object, so format the double into a CString and pass that:
CString str;
str.Format("As string: %g", double);
AfxMessageBox(str);
Edit: If you want the value displayed as an integer (no value after decimal point) then use this instead:
str.Format("As string: %d", (int)double);
That's because ost.str() is not a CString, but rather a C++ string object. You need to convert that to CString: new CString(ost.str()).
Depending on your Unicode settings you need
std::ostringstream ost;
ost << std::setprecision(2) << double_value;
std::cout << "As string: " << ost.str() << std::endl;
AfxMessageBox(ost.str().c_str());
or
std::wostringstream ost;
ost << std::setprecision(2) << double_value;
std::wcout << L"As string: " << ost.str() << std::endl;
AfxMessageBox(ost.str().c_str());
This is needed because CString has a constructor for const char* or const wchar_t*. There is no constructor for std::string or std::wstring. You can also use the CString.Format which has the same not typesave problems like sprintf.
Be aware that double conversion is locale dependent. Decimal seperator will depend on your location.
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();
Hi below is my function:
string Employee::get_print(void) {
string out_string;
stringstream ss;
ss << e_id << " " << type << endl;
out_string = ss.str();
return out_string;
}
e_id and type are int and they contain values from the class Employee. But when I pass them into the stringstream they just clear the string when I try to out put it. But if I don't have a int in the ss << "Some text" << endl; this output fine. What am I doing wrong =S
//Edit
Ok;
This is the calling code:
tmp = cur->get_print();
Where tmp is a string and cur is an Employee Object.
This code...
stringstream out;
out << "Test " << e_id << " " << e_type;
return out.str();
Retruns "Test " and nothing else. If I take out "Test " << my returned string is ""
I'm using GCC 4.2 on Mac OS/X 10.6.2 if that makes any difference.
I too am unable to reproduce this error. As has been mentioned, don't include the endl, as this actually appends a \n and is supposed to flush the write buffer. For this use, it is completely unnecessary and may actually lead to undesirable results...However, the code in your edit/update works just fine for me.
int main(int argc, char* argv[])
{
int e_id = 5;
int e_type = 123456;
stringstream out;
out << "Test " << e_id << " " << e_type;
cout << out.str();
return 0;
}
Produces:
Test 5 123456
My suggestions would be to double check that e_id and e_type are really just native int.
For further testing, you may want to force a cast on the values to see if it helps as such:
out << "Test " << (int)e_id << " " << (int)e_type;
Since I'm unable to reproduce this error, I'm afraid I'm unable to help any further. But best of luck to you!
Ok I have no idea what is going on with stringstream I've tried using it in other parts of my code and it doesn't work with integers. Therefore, I have reverted to using the sprintf C function:
string Employee::get_print(void) {
char out[50];
sprintf(out, "%d %d", e_id, e_type);
string output = out;
return output;
}
This returns the string which is needed.
I have moved into Netbeans and I don't have this problem. So it is an issue with Xcode.
I think the endl is not needed. You only need to write endl if you want to write a newline on a file on on std::cout.
Since you write endl, your stringstream will contain a string with 2 lines of which the second is empty. This probably confuses you. Remove the endl to get only one line.
I've got exactly the same problem - GCC and stringstream returning nothing.
As I found out, the trick is that you have to put some text data before anything else into the stringstream.
This code...
stringstream ss(stringstream::out);
ss << 3.14159;
cout << "'" << ss.str() << "'" << endl;
gets you this result:
''
But if we put a single "" inside the stringstream first...
stringstream ss(stringstream::out);
ss << "" << 3.14159;
cout << "'" << ss.str() << "'" << endl;
the result is as expected:
'3.14159'