C ++中的标准c_str()问题 [英] standard c_str() problem in C++

查看:127
本文介绍了C ++中的标准c_str()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在课堂上玩了以下几种功能:

I have craeted following kind of function in a class:

void SetStr(string& s1, string& s2)
 {
 const char* s =(s1+s2).c_str();
 cout<<s<<endl;
 }



从主调用时,控制台上不会打印任何内容.当以下功能起作用时:



On calling it from main nothing is getting printed on console. While the following function works:

void SetStr(string& s1, string& s2)
 {
 cout<<(s1+s2).c_str()<<endl;
 }


有人可以告诉我这是什么问题.
谢谢.


Can someone please tell me what is the problem.
Thank you.

推荐答案

请参阅 ^ ]


应该在语句s1+s2中创建临时字符串对象,所以为什么不明确地放置s3 ? >
It should be creating a temp string object in statement s1+s2, so why not put an s3 explicitly?

string st3 = s1+ s2;
const char* ch = st3.c_str();
cout<<ch;



顺便说一句,
怎么了?
只是cout<<s1+s2首先?



btw, what''s wrong with

just cout<<s1+s2 in the first place?



试试这个


try this

s1.append(s2);
cout << s1 <<endl;


这篇关于C ++中的标准c_str()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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