C++ 如何将此std::字符串转换为std::basic字符串?
目前我有一个C++ 如何将此std::字符串转换为std::basic字符串?,c++,string,std,memcpy,strcpy,C++,String,Std,Memcpy,Strcpy,目前我有一个std:::string名为cipher\u line,我从以下过程中得到: string str_cipher_line; // Get the Offline Mount Point ifstream ifs1; ifs1.open(offlineMountPoint.c_str()); if (ifs1.is_open()) { getline(ifs1, str_cipher_line); } else { cout << "unable to
std:::string
名为cipher\u line
,我从以下过程中得到:
string str_cipher_line;
// Get the Offline Mount Point
ifstream ifs1;
ifs1.open(offlineMountPoint.c_str());
if (ifs1.is_open()) {
getline(ifs1, str_cipher_line);
} else {
cout << "unable to open file" << endl;
return 1;
}
ifs1.close();
我不知道该怎么做。我应该使用
memcpy
还是strcpy
使用std::basic_string
(CPPFerence上的6)从secure_string
或std::copy
构造。反过来也是如此
#include <iostream>
template <typename T>
struct some_other_allocator : std::allocator<T>{};
using other_string = std::basic_string<char, std::char_traits<char>, some_other_allocator<char>>;
int main() {
other_string string1("hello");
//using std::string constructor
std::string string2(string1.begin(),string1.end());
std::string string2_copy;
//using std::copy
std::copy(string1.begin(),string1.end(),std::back_inserter(string2_copy));
std::cout << string1 << std::endl;
std::cout << string2 << std::endl;
std::cout << string2_copy << std::endl;
return 0;
}
#包括
模板
结构some_other_分配器:std::allocator{};
使用other_string=std::basic_string;
int main(){
其他字符串字符串1(“你好”);
//使用std::string构造函数
std::string2(string1.begin(),string1.end());
std::字符串字符串2_副本;
//使用std::copy
std::copy(string1.begin()、string1.end()、std::back_插入器(string2_copy));
std::两者都不能。请使用包含起始迭代器和结束迭代器的构造函数,并传入std::string
的begin()
和end()
。是的,你能详细说明一下吗@samvarshavchikt这并没有解决这个问题,而是养成了用有意义的值初始化对象的习惯,而不是默认地构造它们然后更改它们。也就是说,将ifstream ifs1;ifs1.open(无论什么);
更改为ifstream ifs1(无论什么)
。您不需要调用ifs1.close()
。析构函数可以做到这一点。@PeteBecker谢谢,欢迎您提出好的建议!您的回答代码显示了如何在代码中构造安全字符串
(或其他字符串
)从字符串文字,但我认为提问者想看看如何从std::string
:secure\u string myString{str\u cipher\u line.begin(),str\u cipher\u line.end()};
#include <iostream>
template <typename T>
struct some_other_allocator : std::allocator<T>{};
using other_string = std::basic_string<char, std::char_traits<char>, some_other_allocator<char>>;
int main() {
other_string string1("hello");
//using std::string constructor
std::string string2(string1.begin(),string1.end());
std::string string2_copy;
//using std::copy
std::copy(string1.begin(),string1.end(),std::back_inserter(string2_copy));
std::cout << string1 << std::endl;
std::cout << string2 << std::endl;
std::cout << string2_copy << std::endl;
return 0;
}