简体   繁体   English

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

[英]How to assign a string value to a string variable in C++

Shouldn't this work?这不应该工作吗?

string s;
s = "some string";

Shouldn't this work?这不应该工作吗?

 string s; s = "some string";

Well, actually it's spelled std::string , but if you have a using namespace std;好吧,实际上它的拼写是std::string ,但如果你有一个using namespace std; ( absolutely evil ) or using std::string; 绝对邪恶)或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. (稍微不那么邪恶)在此之前,它应该可以工作 - 前提是您的文件顶部还有一个#include <string>

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.但是请注意,首先将s初始化为空字符串,只是在下一条语句中替换该值是浪费的。 (And if efficiency wasn't your concern, why would you program in C++?) Better would be to initialize s to the right value immediately: (如果你不关心效率,为什么要用 C++ 编程?)最好立即将s初始化为正确的值:

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* .它默认构造一个字符串,然后从const char*分配它。

(Why did you post this question?... did you at least try it?) (你为什么发布这个问题?......你至少尝试过吗?)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM