常用C++代码——整理自己的通用代码

一、文件读写

c语言版本(无顺序添加读取方便)

#include <stdio.h>
typedef struct {
    char a[10];
    char b[11];
}stu;
int main()
{
    stu test = {0};
    FILE *fp;
    fp = fopen("D:\\path", "w+");  // +代表可写,没有权限为只读, b表示二进制,a表示追加(打开或新建,文件存在则打开),r表示打开(文件要存在),w表示新建文件(文件存在则覆盖)
    //"r" "打开一个文本文件,文件必须存在,只允许读
    //"rb" 打开一个二进制文件,文件必须存在,只允许读
    //“rb+”打开一个二进制文件,文件必须存在,允许读写
    //"w" = “wt”新建一个文本文件,已存在的文件将内容清空,只允许写
    if (!fp)
    {
        return 0;
    }
    fwrite(&test, sizeof(test), 1, fp);
    
    stu test2;
    fread(&test2, sizeof(test2), 1, fp);
    fclose(fp);
}

c++版本(格式化读写方便)

#include "stdafx.h"
#include <iostream>
#include <fstream> //打开文件供读写
using namespace std;

struct Game
{
	int num;
	int year;
	string location;
	string first;
	string second;
	string third;
};

int _tmain(int argc, _TCHAR* argv[])
{
	Game game = {0};
	char buffer[256];
	//ios::in读; ios::out写 ios::app追加 ios::binary二进制 ios::nocreate文件不存在不创建
	//ios::noreplace文件不存在才创建 ios::trunc清空原有内容 ios::ate位置移动到文件末尾
	//ios::beg文件头 ios::end文件未 ios::cur当前位置 如:file.seekg(10,ios::cur);
	
	ofstream outfile("C:\\Users\\Administrator\\Desktop\\t11.txt", ios::out);    // 写入数据到文件
	outfile << game.location.c_str() << game.num;   // 写入结构体

	ifstream in_file("C:\\Users\\Administrator\\Desktop\\t11.txt", ios::trunc);	// 读取数据
	Game game2 = {0};
	if (!in_file.is_open())
	{
		std::cout << "error" << std::endl;
		return 0;
	}
	in_file >> buffer;   //只能是char数组

	in_file.close();
	outfile.close();

	return 0;
}

https://blog.csdn.net/qq_29406323/article/details/81261926

二、类型转换

string和其他类型
//C11
string to_string (int val);

//long -> string
long ulDefSiz = 100000;
stringstream ss;
ss << ulDefSize;
string str = ss.str();
OutputDebugStringA(str.c_str());

int和char*
//int-》char*
//1.windows的itoa
int aa = 30;
char c[8];
itoa(aa,c,16);

//2.sprintf
int aa = 30;
char c[8]; 
int length = sprintf(c, "%05X", aa); 
//3.stringstream

//char*->int
int i;
sscanf("17","%d",&i);
sscanf("17","%X",&i);

1  string s = "17";
2  int i = boost::lexical_cast<int>(s);
3  cout<<i<<endl; // 17

string s = "17";
stringstream ss;
ss<<s;
int i;
ss>>i;
cout<<i<<endl;

//std::stoi/stol/stoll等等函数


swprintf_s(wszCspName2, L"\"%s\" \"aaaa\"", wszCspName);  wszCspName和wszCspName2不能同一个


1、显式专换是定义让这个值类型转换成要用的值类型,例,定义int
i=5,想把他专换成char类型,就用显式转换(char)i。隐式转换是系统跟据程序需要而自动转换的,不需要定义,但并不是所有值类型都可以互相转
换,所以有了显式转换。例,int i=5; char j='a'; int n=i+j;因char可以隐式专换为int类型,所以结果n=102。
2、c方式类型转换:(target_type)(value),如int i = 5; char c = (char)(i);
c++方式类型转换:方式有4种
static_cast类似c语言的类型转换
dynamic_cast继承体系直接引用和指针直接的转换
const_cast常量转换,常量转换成非常量,非常量转换成常量
reintepret_cast重新解释转换,重新解释数值的含义,如int转换成char*等

https://www.cnblogs.com/hereis00/p/9994312.html  类型

三、字符串操作

// char数组赋值char数组
char tmp[10] = {0};
char tmp2[10] = "aa\0aaaa";
char *tmp3 = new char[10];
//方法一(tmp主动加\0)
strcpy(tmp, tmp2);	//执行到tmp2的\0结束(末尾加\0)
strcpy(tmp3, tmp2);
printf("strcpy tmp =%s\n", tmp);
printf("strcpy tmp3 =%s\n", tmp);
//方法二(tmp主动加\0)
sprintf_s(tmp, 4, tmp2); //(末尾加\0)//执行到tmp2的\0结束(sprintf第二个参数要在\0之后)
printf("sprintf_s tmp =%s\n", tmp);
//方法三(tmp不主动加\0)
memcpy(tmp, tmp2, 1);
printf("memcpy,tmp = %s\n", tmp);

//清空1
strcpy(tmp, tmp2);
ZeroMemory(tmp, strlen(tmp2));					//全部清空(无使用\0)
printf("ZeroMemory,tmp = %s\n", tmp);
//清空2
strcpy(tmp, tmp2);
memset(tmp, '\0', strlen(tmp)*(sizeof(char)));  //全部之\0,直到遇到tmp的\0
printf("memset,tmp = %s\n", tmp);


//赋值+串接字符串
//拼接:使用string 字符串和字符串
//拼接:使用char *strcat(char *dest, const char *src)   字符串和字符串
//拼接:使用sprinf_s(tmp, 10, "%s%s",tmp2,tmp3) 字符串和其他类型
//拼接:stringstream 字符串和其他类型
//比较 int memcmp(const void *str1, const void *str2, size_t n) == int strncmp(const char *str1, const char *str2, size_t n)
//比较 int strcmp(const char *str1, const char *str2)
//stringstream拼接     aaaa:10
#include <sstream>
char *str = "aaaa";
int port = 10;
stringstream ss;
ss << str;
ss << string(":");
ss << port;

四、效率计算(clock)

#include <stdio.h>
#include <time.h>

// clock_t 是clock()函数的返回值类型
clock_t start, stop;
// 记录被测代码的运行时间,以秒为单位
double duration;

int main()
{
    // 记录开始时间
    start = clock();
    //......代码
    // 记录结束时间
    stop = clock();
    // 计算代码执行花费的时间
    duration = ((double)(stop-start)) / CLK_TCK;   (不除CLK_TCK代表毫秒)

    return 0;
}
时间获取
std::string getDateTime() {
	//system_clock::time_point tp = system_clock::now();
	//time_t raw_time = system_clock::to_time_t(tp);
	//struct tm  *timeinfo = std::localtime(&raw_time);

	//std::stringstream ss;
	//ss << std::put_time(timeinfo, "%Y-%m-%d");
	////ss << std::put_time(timeinfo, "%Y-%m-%d-%H-%M-%S");
	//return ss.str();
	time_t timep;
	time (&timep);
	char tmp[64];
	strftime(tmp, sizeof(tmp), "%Y-%m-%d",localtime(&timep) );
	return tmp;
}


#include “stdio.h” 
#include “stdlib.h” 
#include “time.h” 
int main( void )
 {
    long i = 10000000L; 
    clock_t start, finish; 
    double duration;
    printf( "Time to do %ld empty loops is ", i );
    start = clock(); while( i-- ) ; 
    finish = clock();
    duration = (double)(finish - start) / CLOCKS_PER_SEC;  ///clock是毫秒,除 CLOCKS_PER_SEC代表秒;
    printf( "%f seconds/n", duration ); 
    char tmp[MAX_PATH] = {0};
    sprintf_s(tmp, MAX_PATH, "debug===================%f", duration);
    OutputDebugStringA(tmp);
    system("pause"); 
}

五、错误

	try
	{	...
	}
	catch(boost::exception &e/*std::exception& e*/)
	{
		//std::cout << e.what() << std::endl;
		 std::cerr << boost::diagnostic_information(e);
	}

六、定时器

		//boost::asio::io_service io;
		//boost::asio::deadline_timer timer(io, boost::posix_time::seconds(3));
		//异步
		//timer.async_wait(&print);
		//io.run();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章