2012
Jun
12

大部分的 C++ 用法,可以参考以下的网站。

字串相关

将字串转成大写

Example
  1. #include <iostream>
  2. #include <string.h>
  3. #include <algorithm>
  4.  
  5. int main () {
  6. string method = "http";
  7. std::transform(method.begin(), method.end(), method.begin(), ::toupper);
  8. }

将字串 string 转成数字 int

string to int
  1. string s = "1";
  2. int a = atoi(s.c_str());

将字串串接 , sprintf

Example
  1. char* buff = new char[200];
  2. sprintf(buff , "%s.%s", a, b);
  3. // %# %s 接的值不能用 string ,需转换 string.c_str()

Memory locate and free

有一次想用 C 语言写个小功能,在写程式的途中有用到一些字串的 buff,於是我定义了 char* buff = new char(12),想说来个 12 bytes 的字串,最后再加一句 delete[] buff,来移除 memory,结果出错了,错误讯息:「free(): invalid next size (fast)」,gcc 也算贴心了,帮你写出问题,不过我看来看去,完全找不到任何逻辑有错的地字,一直过了几天,才发现小括号是直接给值的意思,不是分配记忆体呀!!! 所以我一直在指定 buff 这个变数等於字串(12),总个超傻眼,正确的分配记忆体方式,请用中括号。

Example
  1. //char* buff = new char(12) // wrong !
  2. char* buff = new char[50];
  3. delete[] buff

string to char

Example
  1. char *res = new char[500];
  2. strcpy(resr, header.c_str());

Throw Exception

如果你想在 c 语言中使用 exception ,Compile 时的指令要加上 -fexceptions 才能 compile 成功。

binding.gyp: "cflags_cc": ["-fexceptions"]
Example
  1. #include <stdexcept>
  2. #include <exception>
  3.  
  4. throw std::runtime_error("exception message");

windows string to TCHAR

Example
  1. string paramStr = "xxxxxxxxxxxxx";
  2. TCHAR *postData;
  3. postData = (TCHAR*)paramStr.c_str();

const char* 裁字

如果我想撷取 bc 这两个字。

Example
  1. char* tx = (char*) malloc (sizeof(char) * 3);
  2. const char* p = { "abcde" };
  3. memcpy(tx, p + 1, 2);
  4. *(tx + 2) = '\0';

回應 (Leave a comment)