4

I am programming in C++.

As basic as this question is I cannot seem to find an answer for it anywhere. So here is the problem:

I want to create a C-style string however I want to put an integer variable i into the string. So naturally, I used a stream:

stringstream foo;
foo
                << "blah blah blah blah... i = " 
                << i
                << " blah blah... ";

However, I need to somehow get a C-style string to pass to a function (turns out foo.str() returns an std::string). So this is technically a three part question --

1) How do I convert std::string to a C-style string?

2) Is there a way to get a C-style string from a stringstream?

3) Is there a way to use a C-style string directly (without using stringstreams) to construct a string with an integer variable in it?

Sergey K.
  • 24,894
  • 13
  • 106
  • 174
user1413793
  • 9,057
  • 7
  • 30
  • 42
  • 1
    The easiest way would be to just make an `itos` function using a stream, and use `itos (564).c_str()`, where the function returns `foo.str()`. – chris Jun 09 '12 at 04:49
  • 1
    `sprintf()` and the buffer-overflow-safe `snprintf()` will populate a cstring formatted as you specify. – jedwards Jun 09 '12 at 04:50

3 Answers3

14

1) How do I convert std::string to a C-style string?

Simply call string.c_str() to get a char const*. If you need a mutable _C-style_ string then make a copy. The returned C string will be valid as long as you don't call any non-const function of string.

2) Is there a way to get a C-style string from a stringstream?

There is, simply strstream.str().c_str(). The returned C string will be valid only until the end of the expression that contains it, that means that is valid to use it as a function argument but not to be stored in a variable for later access.

3) Is there a way to use a C-style string directly (without using stringstreams) to construct a string with an integer variable in it?

There is the C way, using sprintf and the like.

K-ballo
  • 80,396
  • 20
  • 159
  • 169
3

You got halfway there. You need foo.str().c_str();

  1. your_string.c-str() -- but this doesn't really convert, it just gives you a pointer to a buffer that (temporarily) holds the same content as the string.
  2. Yes, above, foo.str().c_str().
  3. Yes, but you're generally better off avoiding such things. You'd basically be in the "real programmers can write C in any language" trap.
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • I've heard that joke about FORTRAN, but since when did it become hip to bash on C :-(. – jedwards Jun 09 '12 at 05:21
  • @jedwards: I'm not bashing on C at all -- but I think it's better to pick one or the other than write bits of C++ with decidedly non-C++ idioms mixed in. – Jerry Coffin Jun 09 '12 at 05:48
-1
  1. this is realy simple

    #include <afx.h>
    std::string s("Hello");
    CString cs(s.c_str());
    
  2. no

  3. yo can use sprintf to format a c-style string

CPlusSharp
  • 881
  • 5
  • 15