1. 向文件中写入浮点数的格式
1 | double pi = 3.14; |
2. 字符串分割方法
使用 strtock 函数进行字符串分割
1
2
3
4
5
6
7
8
9
10
11
12
13char *strtok(char *str, const char *delim);
strtok 函数线程不安全,可以使用 strtok_r 替代
void strtok_test() {
char s[] = "Golden global View,disk * desk";
const char* delim = " ,*";
char* p;
p = strtok(s, delim);
while (p) {
printf("%s\n", p);
p = strtok(NULL, delim);
}
}使用 STL 进行字符串分割
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38// 使用 find、substr 来分割
std::vector<std::string> split(std::string str,std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str+=pattern; // 扩展字符串以方便操作
int size=str.size();
for(int i=0; i<size; i++)
{
pos=str.find(pattern,i);
if(pos<size)
{
std::string s=str.substr(i,pos-i);
result.push_back(s);
i=pos+pattern.size()-1;
}
}
return result;
}
// 使用 find_first_not_of 来分割
void Tokenize(const string& str, vector<string>& tokens, const string& delimiters)
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
}
}使用 boost 库
1
2
3string s = "sss/ddd,ggg";
vector<string> vStr;
boost::split( vStr, s, boost::is_any_of( ",/" ), boost::token_compress_on );