如何将std :: string转换为C样式的字符串 [英] How to convert an std::string to C-style string

查看:177
本文介绍了如何将std :: string转换为C样式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用C ++编程。

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:

我想创建一个C风格的字符串,但是我想将一个整数变量i放入字符串中。很自然地,我使用了一个流:

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... ";

但是,我需要以某种方式获取C风格的字符串以传递给函数(结果为foo .str()返回std :: string)。所以从技术上讲这是一个三部分的问题-

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)如何将std :: string转换为C风格的字符串?

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

2)是否可以从字符串流中获取C风格的字符串?

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

3)是否可以使用C-直接样式化字符串(不使用stringstreams)以构造其中带有整数变量的字符串?

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?

推荐答案


1)如何将std :: string转换为C样式的字符串?

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

只需调用 string .c_str()以获得 char const * 。如果您需要 mutable _C-style_字符串,请进行复制。只要您不调用 string 的任何非常量函数,返回的 C字符串就有效。

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)有没有办法从字符串流中获取C风格的字符串?

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

这里只是 strstream.str()。c_str()。返回的 C字符串仅在包含它的表达式的末尾才有效,这意味着将其用作函数参数是有效的,但不能存储在变量中以备后用。 / p>

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)是否有一种方法可以直接使用C样式的字符串(不使用stringstreams)来构造其中带有整数变量的字符串?

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?

C方式,使用 sprintf 等。

这篇关于如何将std :: string转换为C样式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆