Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ how to use a variable in a string

Tags:

c++

string

The following code doesn't work:

string currency;
currency = "EURUSD";

system("lynx -dump 'http://somesite.com/q?s="+currency+"=X' > file.txt");

How do I use currency inside this line of C++'s system() call?

This is my error:

Error value:
main.cpp: In function ‘int main()’:
main.cpp:22:84: error: cannot convert ‘std::basic_string<char>’ to ‘const char*’ for argument ‘1’ to ‘int system(const char*)’
make: *** [main.o] Error 1
BUILD FAILED (exit value 2, total time: 890ms)

In PHP I use . to join strings, but in C++ I am not sure of the syntax.

like image 348
Baoky chen Avatar asked Jul 12 '26 14:07

Baoky chen


2 Answers

Using stringstream:

#include <sstream>
string currency;
currency = "EURUSD";
std::stringstream ss;
ss << "lynx -dump 'http://somesite.com/q?s=" << currency << "=X' > file.txt";
system(ss.str().c_str());
like image 165
perreal Avatar answered Jul 15 '26 04:07

perreal


std::string::c_str() will give you a char* (const'd somehow) that you can use in C string functions. But you should consider creating a std::string that contains the full command first.

like image 32
Ignacio Vazquez-Abrams Avatar answered Jul 15 '26 03:07

Ignacio Vazquez-Abrams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!