0

I have a string with non-ASCII characters, for example std::string word ("żółć"); or std::string word ("łyżwy"); I need to convert it properly to const char * in order to call system(my_String_As_A_Const_Char_Pointer);

I'm working on Linux.

How can I do it?

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
enedil
  • 1,605
  • 4
  • 18
  • 34
  • 1
    `word.c_str()` might work – Bojangles Dec 24 '13 at 15:11
  • `c_str()` gives you a `const char*`. Or is your question about encoding? In which case you need to be clear about what encoding you are using, and what encoding `system` needs. So, tell us more about encodings. – David Heffernan Dec 24 '13 at 15:12
  • Thanks, but the problem was in other place, which isin't related to the question. `c_str()` works fine. – enedil Dec 24 '13 at 15:28
  • 3
    I don't quite understand why you ask a question and concentrate on non-ASCII characters, and then accept an answer that ignores that aspect. If encoding is not an issue for you, then you should ask how to get a `const char*` from a `std::string`. A trivial question that has been asked a million times already. – David Heffernan Dec 24 '13 at 15:28

2 Answers2

4

You can use the std::string::c_str member function. It will return a const char * that can be used in functions that accept that type of argument. Here's an example:

int main(int, char*[]) {
    std::string word("żółć");
    const char* x = word.c_str();
    std::cout << x;
}

And here's a live example.

Shoe
  • 74,840
  • 36
  • 166
  • 272
1

With these conversions the only thing to care about is mixing wide chars with normal chars (which fails horribly). You are using a std:string, so c_str() is fine for pulling out a const char* to pass to some other library call.

RichardPlunkett
  • 2,998
  • 14
  • 14