• 使用sstream进行int转换string的注意事项


    个人网站 :http://39.106.25.239/  

    1.引入sstream文件

    2.使用stringstream 声明

    3.使用一次sstream转换后要执行成员函数.clear() 来清除stringstream中的字符串 否则,永远只对第一次的字符串生效。


    转载自:http://www.cnitblog.com/30701735/articles/44699.html

    C++标准库中的stringStreams是从iostream类派生而来的,也因为其内部重载了针对各重内置类型和某些标准库类型(如string)的确"<<"和">>"操作符,所以可以用来进行类型之间的转换.看起来比较简单,但因为一般的C++书籍对其介绍比较少,经过测试之后发觉有些东西还是需要注意的.
    例如以下代码段:

     1    int a;
     2    // 字符串流
     3    stringstream strStream;
     4    strStream << "345";
     5    strStream >> a;
     6    cout << a << endl;
     7    strStream.clear();
     8    strStream << "34561";
     9    strStream >> a;
    10    cout << a << endl;
    输出为:

    但如果稍微改动下代码:
        strStream << "345a";
        strStream >> a;
        cout << a << endl;
        strStream.clear();
        strStream << "34561";
        strStream >> a;
        cout << a << endl;

    则输出结果就变为:

    为什么呢?因为 strStream << "345a";
     strStream >> a;这两句并未将strStream内的内容读取完毕导致strStream.clear()无效,程序并没有清除strStream中的字符串,所以在下次从strStream中输出的时候还是会读取到345.
  • 相关阅读:
    themes、skins
    使用GreyBox实现Ajax模式窗口
    .net最小化到系统托盘
    asp.net自定义控件
    [转]SQL函数的简短说明
    prototype1.4 和1.5
    [转]Oracle PL/SQL 编程手册(SQL大全)
    更新同一张表中的数据的方法
    js中eval()的作用
    asp.net中的中文和特殊字符的处理方式!
  • 原文地址:https://www.cnblogs.com/lingluan533/p/12537307.html
Copyright © 2020-2023  润新知