一、四舍五入
开始写法如下:
int main()
{
float value = 3.141592;
std::stringstream ss;
ss << std::fixed << std::setprecision(3) << value;
ss >> value;
cout << std::to_string(value) << endl;
return 0;
}
由于需要返回字符串格式,故开始想着利用 to_string() 方法对其转化,但输出的是 3.142000,而不是想要的 3.142。调整为下述写法直接调用 str() 方法就好啦:
int main()
{
float value = 3.141592;
std::stringstream ss;
ss << fixed << setprecision(3) << value;
cout << ss.str() << endl;
return 0;
}
二、分割字符串
有一段字符串需要按指定字符分隔开,可以用 strtok() 方法:
std::string input = "3|4|5|6";
std::strcpy(p, input.c_str());
char* s = std::strtok(p, "|");
while (s != NULL) {
cout << s << endl;
s = std::strtok(NULL, "|");
}
注意在循环体调用时,第一个参数需传 NULL,此处可参考 man 手册解释:
DESCRIPTION
This interface is obsoleted by strsep(3).The strtok() function is used to isolate sequential tokens in a null-terminated string, str. These tokens are separated in the string by at least one of the characters in sep. The first time that strtok() is called, str should be specified; subsequent calls, wishing to obtain further tokens from the same string, should pass a null pointer instead. The separator string, sep, must be supplied each time, and may change between calls.
The implementation will behave as if no library function calls strtok().
The strtok_r() function is a reentrant version of strtok(). The context pointer last must be provided on each call. The strtok_r() function may also be used to nest two parsing loops within one another, as long as separate context pointers are used.
The strtok() and strtok_r() functions return a pointer to the beginning of each subsequent token in the string, after replacing the token itself with a NUL character. When no more tokens remain, a null pointer is returned.
目前就这些,以后再补充。欢迎交流~