天天看點

常用C++代碼——整理自己的通用代碼一、檔案讀寫二、類型轉換三、字元串操作四、效率計算(clock)五、錯誤六、定時器

一、檔案讀寫

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();
           

繼續閱讀