0

In my C++ code, I am executing some commands using python as follows:

std::string word = "Something";
std::cout << word;                         //will execute using C++
PyRun_SimpleString("import sys");          // will execute using Python

The problem is how to pass word to Python ?

I want something like this: PyRun_SimpleString("Hello %" %word);

In Python you can do: "Hello {}".format(word) and the result "Hello Something"

I found something like this: sprintf(str, "hello %s", word); But the problem is printf or sprintf will send it to console and will not return the value of word.

3
  • 3
    sprintf will not send it to the console. Commented Apr 24, 2019 at 17:04
  • Thank you. so can I use it in my example like this: new_word = sprintf(str, "Hello %s", word); ? Commented Apr 24, 2019 at 17:07
  • sprintf() returns the number of characters copied into str. You would need new_word = str; after sprintf() exits. But you really shouldn't be using sprintf() anyway. That is the C way of formatting strings. The C++ way is to use std::string::operator+ or a std::ostringstream instead Commented Apr 24, 2019 at 17:08

1 Answer 1

3

In C++, you use the + operator to concatenate std::string objects.

PyRun_SimpleString() takes a const char* as input. std::string has a c_str() method for obtaining a const char* for the string.

So, you can do this:

std::string s = "Hello " + word;
PyRun_SimpleString(s.c_str());

Or simply this:

PyRun_SimpleString(("Hello " + word).c_str());

Alternatively, you can use a std::ostringstream instead to build up a formatted string:

std::ostringstream oss;
oss << "Hello " << word;
PyRun_SimpleString(oss.str().c_str());
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much that is really helpful.
Sidenote: There's no operator+ for numerical values (int, unsigned long, float, double, ...), only for character, C-strings and std::string. So if you need the former, you'd be using the std::ostringstream variant...

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.