c++小tips

一、四舍五入        

        开始写法如下:

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.

        

        目前就这些,以后再补充。欢迎交流~ 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值