开发者

How to assign a string value to a string variable in C++

开发者 https://www.devze.com 2022-12-31 03:51 出处:网络
Shouldn\'t this work? string s; s = \"some string开发者_JAVA百科\"; Shouldn\'t this work? string s; s = \"some string\";

Shouldn't this work?

string s;
s = "some string开发者_JAVA百科";


Shouldn't this work?

string s;
s = "some string";

Well, actually it's spelled std::string, but if you have a using namespace std; (absolutely evil) or using std::string; (somewhat less evil) before that, it should work - provided that you also have a #include <string> at the top of your file.

Note, however, that it is wasteful to first initialize s to be an empty string, just to replace that value in the very next statement. (And if efficiency wasn't your concern, why would you program in C++?) Better would be to initialize s to the right value immediately:

std::string s = "some string" 

or

std::string s("some string");


Yes!

It's default constructing a string, then assigning it from a const char*.

(Why did you post this question?... did you at least try it?)


use header file string.h or bits/stdc++.h then try s.assign("some string");

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号