zoukankan      html  css  js  c++  java
  • 【c++】字符串流输出恢复状态问题

    缘起

    #include <iostream>
    #include <sstream>
    using namespace std;
    int main()
    {
        istringstream iss;
        string str1, str2, str3, str4, str5, str6;
        iss.str("I love you");
        iss >> str1 >> str2 >> str3;
        cout << str1 << " " << str2 << " "<< str3 << endl;
        iss.str("I hate you");
        iss >> str4 >> str5 >> str6;
        cout << str4 << " " << str5 << " "<< str6 << endl;
    }

    期待输出

         

    可以结果是

        

    问题

        没有输出“I  hate you"。究竟是什么原因导致 流没有输出到字符串中?

    一番折腾知道,此时流的eof为1(已经达到结束符),此时必须用函数clear()把所有的状态值设为有效状态值。经过修改程序如下:

    #include <iostream>
    #include <sstream>
    using namespace std;
    int main()
    {
        istringstream iss;
        string str1, str2, str3, str4, str5, str6;
        iss.str("I love you");
        cout << "before" << iss.str() << endl;
        iss >> str1 >> str2 >> str3;
        cout << str1 << " " << str2 << " "<< str3 << endl;
        
        cout << "eofbit:" << iss.eof() << endl;
        iss.clear();
        cout << "eofbit:" << iss.eof() << endl;
    
        iss.str("I hate you");
        cout << "after:" << iss.str() << endl;
        iss >> str4 >> str5 >> str6;
        cout << str4 << " " << str5 << " "<< str6 << endl;
    }

    正确结果

    程序用到知识

  • 相关阅读:
    yield* 表达式
    Set 对象和WeakSet对象
    洗牌算法
    filter() 方法创建一个新数组
    UTF8文件带BOM引起的问题
    ios的白屏坑
    css的字体样式怎么写
    npm全局安装失效修复
    nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)解决方案
    linux下nginx的安装及配置
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3240775.html
Copyright © 2011-2022 走看看