This is a very simple question and I feel stupid for asking it, but I am pressed for time and I need to figure it out :)
I just need to know how to make a string that contains text and other variables. For instance in Java I can just do this:
String someString;
for(int i = 0; i>10; i++){
someString = ("this text has printed " + i + " times"); //how do I create this line in C++?
System.out.println(someString);
i++;
}
EDIT 4:
Ok, Rahul G's answer below works pretty good, and the program compiles and ok, but when I run it instead of getting the string I want for the file name, I get a bunch of numbers. For instance: << "frame " << i << " .jpg"
creates: "013679000.jpg" instead of "frame 0.jpg" like I want. Any thoughts?
for(int i = 0; frames; i++)
{
frame = cvQueryFrame(capture);
std::string s = static_cast<std::ostringstream &>(std::ostringstream() << argv[1] << i << " .jpg").str();
cvSaveImage(s.c_str(), frame);
}
You can use stringstreams for this:
for (int i = 0; i < 10; i++) {
std::ostringstream ss;
ss << "this text has printed " << i << " times";
std::cout << ss.str() << std::endl;
}
Java:
int i = 5;
double d = 2.23606798;
String s = "Square root of "+i+" is "+d;
C++:
int i = 5;
double d = 2.23606798;
std::ostringstream oss;
oss << "Square root of " << i << " is " << d;
std::string s = oss.str();
// If you need C style string...
char const *s0 = s.c_str();
Please note that the std::ostringstream
class resides in <sstream>
header.
Edit:
Your code (corrected):
for(int i = 0; frames; i++) {
frame = cvQueryFrame(capture);
std::ostringstream oss;
oss << "frame " << i << " .jpg";
cvSaveImage(oss.str().c_str(), frame);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With