c 一些問題總結

2021-09-25 11:51:08 字數 3121 閱讀 7351

這裡總結一些c++常遇到的問題

不同型別之間的轉換。

//1 string --> const char*

std::string s_1 = "lsw";

const char *cs_1 = s_1.c_str();

printf("const char * cs is %s \n", cs_1);

//2 const char* --> string

const char *cs_2 = "lsw";

std::string s_2(cs_2);

printf("std::string s_2 is %s\n", s_2.c_str());

//3 string --> char*

std::string s_3 = "lsw";

char *cs_3;

auto len = s_3.length();

cs_3 = new char[len + 1];

char *res_3 = strcpy(cs_3, s_3.c_str());

printf("string to char* === %s", res_3);

//4 char* --> string

char *cs_4 = "lsw"; //c++ 11標準中這裡有警告,不推薦這麼用

std::string s_4(cs_4);

//5 const char* --> char *

const char* cs_5 = "lsw";

char *cs_6 = new char[100];//足夠大

char *res_5 = strcpy(cs_6, cs_5);

printf

("cs_6 = %s \n", cs_6);

string, const char* ---> int, double, long

double	atof(const char *);

int atoi(const char *);

long atol(const char *);

int --- > string

char buff[100];

sprintf(buff, "%d", 990);

std::string sb = buff;

已知strcpy的函式原型:char *strcpy(char *strdest, const char *strsrc)其中strdest 是目的字串,strsrc 是源字串。不呼叫c++/c 的字串庫函式,請編寫函式 strcpy

/**

已知strcpy函式的原型是

char *strcpy(char *strdest, const char *strsrc);

其中strdest是目的字串,strsrc是源字串。

(1)不呼叫c++/c的字串庫函式,請編寫函式 strcpy

(2)strcpy能把strsrc的內容複製到strdest,為什麼還要char * 型別的返回值?

答:為了 實現鏈式表示式。

例如 int length = strlen( strcpy( strdest, 「hello world」) );

*/char *mystrcpy(char *str1, const char *str2)

return res;

}int mystrlen(const char* str)

return len;

}

其他的一些知識

1、sizeof 和 strlen

char a = "12";

//這裡sizeof輸出 3 是a的位數包括 '\0'

cout << sizeof(a) << endl;

char *p = a;

//輸出 8,是指標p的位元組數

cout << sizeof(p) << endl;

char *str = "12";

//輸出 2,不包含'\0'

cout << strlen(str) << endl;

2、巨集定義

#define min(a, b) ((a)>=(b)?(b):(a))

3、string定義

.h//

// mystring.h

// testcpp

//// created by lsw on 14-12-24.

//#ifndef __testcpp__mystring__

#define __testcpp__mystring__

#include class mystring ;

#endif /* defined(__testcpp__mystring__) */

.cpp

//// mystring.cpp

// testcpp

//// created by lsw on 14-12-24.

//#include "mystring.h"

#include #include mystring::mystring(const char* str) else

}mystring::mystring(const mystring &other)

mystring::~mystring()

mystring & mystring::operator=(const mystring &other)

delete m_data;

auto len = strlen(other.m_data);

m_data = new char[len + 1];

assert(m_data != nullptr);

strcpy(m_data, other.m_data);

return *this;

}int mystring::mystrlen(const char *str)

return len;

}

C 一些問題

1 if else語句和switch case語句的效率分析對比 switch效率高。switch的效率與分支數無關,當只有分支比較少的時候,if效率比switch高,因為switch有跳轉表。分支比較多,那當然是switch 根據大量的實際程式測試 不考慮不同的編譯器優化程度差異,假設都是最好的優...

Mysql一些問題的總結

1 between 和 and 是單向的。也就是說,between a and b 中,a一定要在b 的前面。否則會查空。記錄下。2 mysql 不支援 full join first 函式和last 函式,top語法 3 mysql 不支援select into 直接備份 但是可以使用insert...

docker 中一些問題總結!

上篇介紹了docker 這篇總結一下遇到的其他問題 一.問題 package docker ce 3 19.03.8 3.el7.x86 64 requires containerd.io 1.2.2 3,but none of the providers can be installed 這種是版...