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;
    }

    正确结果

    程序用到知识

  • 相关阅读:
    多文档上传文件
    每个程序员都有一颗想改变世界的心
    获取在服务器上面的路径
    串行口通信(二)之串行口方式0
    串行口通信(一)
    keil进阶教程
    keil教程之新建软件工程
    定时器2的使用
    定时器之计数器应用
    定时器(二)
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3240775.html
Copyright © 2011-2022 走看看