1:改变控制台输出的文本格式,特别是中文编码的问题,转换成UTF-8
system("chcp 65001");
system("cls");
2:改变当前文件索引路径(改为运行文件路径)
#include <direct.h> //需要包含这个文件
// change current run path
std::string rootPath = "";
#ifdef WIN32
char* buf = _getcwd(nullptr, 0);
if (buf) {
rootPath = std::string(buf) + "\\";
delete buf;
buf = nullptr;
}
#endif
_chdir(rootPath.c_str());
3:c++ 读文件
std::fstream myfile("./value.txt", std::ios::in);
if (!myfile.is_open()) {
std::cout << "file is open fail"<< std::endl;
}
std::string temp;
while (getline(myfile, temp)) {
std::cout << temp << std::endl;
}
myfile.close();
4:c++ map判断元素是否存在
//1、Count,返回1则存在,返回0则不存在
if (1 == wellInfoMap.count(key))
{
balabala
}
//2、Find,得到的结果不是map的end则存在,否则不存在
if (wellInfoMap.end() != wellInfoMap.find(key))
{
pilipala
}
5:数据替换,中间替换分隔符
/**
* 数据转换
* @param data
* @param <T>
* @return
*/
template <typename T>
static std::string convertTo(std::vector<T> data,std::string splidStr) {
std::string buf;
for (unsigned int i = 0; i < data.size(); i++) {
buf.append(std::to_string(data[i]));
if (i < data.size() - 1) {
buf.append(splidStr);
}
}
return buf;
}
6:c++写的拼接字符串的函数
template <typename... Args>
std::string stringFormat(const std::string &format, Args... args)
{
size_t size = (size_t)snprintf(NULL, 0, format.c_str(), args...) + 1;
std::unique_ptr<char> buf(new char[size]);
snprintf(buf.get(), size, format.c_str(), args...);
return std::string(buf.get(), size - 1);
}
类似使用:stringFormat(“%s %s”, “hello”,“world”);
7:c++ 替换字符串
str.erase(std::remove(str.begin(), str.end(), ‘a’), str.end());
8:c++写文件
FILE* fp = fopen("out.txt","wb");
if(!fp)
return;
fprintf(fp,"%s",value);
fclose(fp);
9:c++ vector拷贝赋值
// 这里用vector<char>拷贝string为例
std::vector<char>result;
std::string str("data");
result.assign(str.begin(),str.end());
10:如果在linux编译中遇到std::make_unique问题,可能是因为c++11为提供make_unique操作,c++14提供了该函数,所以需要做兼容
namespase utils{
#include <memory>
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&& ... params)
{
return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
}