1. 程式人生 > >c++型別轉換大全

c++型別轉換大全

C++語法整理:

1,  char轉string

1)      string.insert(s.begin(), char)

2,  char*轉string

1)      string(char*)

2)      string = char*

3,  int轉string

1)      char buf[10];

sprint(buf, “%d”, 100);

string b = buf;

2)      stringstream ss; (sstream.h)

ss<<int;

string s = ss.str();

4,  string轉char*

1)      const char* = string.data()    ->沒有”\n”

2)      const char* = string.c_str()    ->有”\n”

3)      string.copy(char[], copyNum, beginLocation)

4)      string str;

char buf[10];

strcpy(buf, str.c_str());

5,  string轉char

1)      string.c_str()[i]

6,  string轉int

1)      int = atoi(string.c_str()) (cstdlib.h)

2)      int = boost::lexical_cast<int>(string)

3)      int i;  stringstream ss(string);

ss>>i;

7,  string轉double

1)      double = atof(string.c_str()) (cstdlib.h)

2)      double d;  stringstream ss(string);

ss>>d;

8,  去限定符const

1)      const_cast<new_type>(expression)

2)      int* = (int*)(&const int)

補充:

·        static_cast <new_type> (expression)

·        reinterpret_cast <new_type> (expression)

·        dynamic_cast <new_type> (expression)

9,  QT中c++ string轉QString

QString = QString(QString::fromLocal8Bit(string.c_str()))

10,QString轉string

string((const char*)QString.toLocal8Bit())

11, c++檔案讀寫

         讀取檔案:

                   ofstreamf(“output.txt”);  /  fstream f(“output.txt”)

                   f<<…

         寫檔案:

                   Ifstreamf(“input.txt”);    / fstream f(“input.txt”)

                   f>>…

         f.close();

         feof()是否到達檔案末尾

         fewind()復位檔案定位器到檔案開始處

         fgets(str,int,file)讀取指定個數的字元或一行