Преобразование часто используемых типов данных С++
Часто возникают сложности с преобразованием типов данных, а их в языках достаточное количество. По этому решил составить маленькую шпаргалку, разделенную на категории с наиболее часто используемыми типами данных в языке С++.
Можно оставлять в комментариях поправки к статье и пожелания. 💭💭💭
int to std::string | std::string to int | std::string to double
// int to std::string
#include <string>
std::string str = std::to_string(10);
// std::string to int
std::string str="10";
int i = atoi(str.c_str());
// int to std::string | std::string to int
#include <sstream>//подключение библиотеки
std::string str,str2=”5”;
std::stringstream s1, s2;
int i = 10;
s1 << i; s1 >> str; //int to std::string
s2 << str2; s2 >> i; //std::string to int
// std::string to double
std::string str = "5.5";
double d = (double)std::atof(str.c_str());
sstd::string to char | char to std::string
// std::string to char[256]
std::string str = "text";
char sz[256];
strcpy_s(sz, str.c_str());
// char* to std::string
#include <sstream>
std::stringstream s;
std::string str;
char* sz = "text";
s << sz;
str = s.str();
// char[] char* to std::string
char *sz = "text";
std::string s1(sz);
char sz[] = "text";
std::string s2(sz);
// LPWSTR to std::string
#include <atlstr.h>
LPWSTR lpstr = L"text";
std::string str = CW2A((LPWSTR)lpstr);
// std::string to LPCWSTR
#include <Windows.h>
std::string str = "text";
std::wstring msg = s2ws(str);
LPCWSTR lpstr = msg.c_str();
//объявим и подключим функцию для преобразования
std::wstring s2ws(const std::string& s)
{//для преобразования std::string to std::wstring
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}//std::wstring s2ws
// const WCHAR* to const char*
#include <comdef.h>
const WCHAR *wch = L"text";
_bstr_t b(wch);
const char *ch = b;
Присоединяйтесь — мы покажем вам много интересного
Присоединяйтесь к ОК, чтобы подписаться на группу и комментировать публикации.
Нет комментариев