2

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.

0

4 Answers 4

5

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());
Sign up to request clarification or add additional context in comments.

1 Comment

+1: Better than my answer as this will work with "variables" other than std::string (as long as they have the appropriate operator <<()defined. This also allows formatting via manipulators.
2

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.

4 Comments

What do you mean by const'd somehow?
@chris: There's 3 different ways to const a pointer to a non-void type. I can't recall which way is used here.
@IgnacioVazquez-Abrams, It returns const char *.
@chris: Well there we go then.
2

You can't + a std::string to a char []. Although you can + a char [] to a std::string.

I suggest using std::strings and getting the const char* just for the call to system():

string const currency = "EURUSD";
string const command_line = "lynx -dump 'http://somesite.com/q?s=" + currency + "=X' > file.txt";

system(command_line.c_str());

Comments

0

That should work.

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

3 Comments

Johnsyweb was faster typing ;-)
command.c_street? You've been watching too much Coronation Street.
Frickin' mobile's auto-completion ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.