有没有办法在 C++ 中将字符串从 const char*
复制到 string
?我正在尝试做这样的事情:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
string s1;
const char* pStr = "Sample Text";
for(int i = 0; i < strlen(pStr); i++)
s1[i] = pStr[i];
cout<<s1<<endl;
return 0;
}
在我的情况下 s1
结果是空的。
原文由 user7314153 发布,翻译遵循 CC BY-SA 4.0 许可协议
看一下 cppreference , --- 的构造函数(
std::basic_string
std::string
的模板类),替代(5):