如何在 C++ 中将字符串值分配给字符串变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2894006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:25:26  来源:igfitidea点击:

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

c++stringvariablesg++

提问by neuromancer

Shouldn't this work?

这不应该工作吗?

string s;
s = "some string";

回答by sbi

Shouldn't this work?

string s;
s = "some string";

这不应该工作吗?

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.

好吧,实际上它是拼写的std::string,但是如果您在此之前有using namespace std;绝对邪恶)或using std::string;(邪恶程度稍低),它应该可以工作 - 前提是您#include <string>的文件顶部也有一个。

Note, however, that it is wasteful to first initialize sto 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 sto the right value immediately:

但是请注意,首先初始化s为空字符串是浪费的,只是为了在下一个语句中替换该值。(如果您不关心效率,为什么要用 C++ 编程?)最好s立即初始化为正确的值:

std::string s = "some string" 

or

或者

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

回答by Stephen

Yes!

是的!

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

默认构造一个字符串,然后从const char*.

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

(你为什么发布这个问题?...你至少尝试过吗?)

回答by Sabyasachi Behera

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

使用头文件 string.h 或 bits/stdc++.h 然后尝试 s.assign("some string");