c++ 常用知识

类型转换

string 转 int

How can I convert a std::string to int?
Easiest way to convert int to string in C++
In C++11 there are some nice new convert functions from std::string to a number type.

So instead of

  • string->int
    1
    atoi( str.c_str() )

you can use

  • string->int
    1
    std::stoi( str )

where str is your number as std::string.

There are version for all flavours of numbers:

1
long stol(string), float stof(string), double stod(string),...

  • int->string
    1
    std::string s = std::to_string(42);

see http://en.cppreference.com/w/cpp/string/basic_string/stol

文件操作

Input/output with files

写文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile ("example.txt");
if (myfile.is_open()) {
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;
}

读文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open()) {
while ( getline (myfile,line) ) {
cout << line << '\n';
}
myfile.close();
} else {
cout << "Unable to open file";
}
return 0;
}

字符串操作

字符串split

Parse (split) a string in C++ using string delimiter (standard C++)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

// Output:

scott
tiger
mushroom

md5代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <openssl/md5.h>
#include <string.h>
#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

int main() {
MD5_CTX ctx;
unsigned char outmd[16];
int i = 0;
memset(outmd, 0, sizeof(outmd));
MD5_Init(&ctx);
MD5_Update(&ctx, "hel", 3);
MD5_Update(&ctx, "lo", 2);
MD5_Final(outmd, &ctx);
for (i = 0; i < 16; i < i++) {
printf("%02X", outmd[i]);
}
printf("\n");
return 0;
}

进制转换

16进制字符串转为10进制数字

1
2
3
4
uint64_t number;
std::stringstream ss;
ss << std::hex << hex_str;
ss >> number;