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

    正确结果

    程序用到知识

  • 相关阅读:
    51nod 1117 聪明的木匠:哈夫曼树
    51nod 1010 只包含因子2 3 5的数
    51nod 2636 卡车加油
    51nod 2989 组合数
    51nod 2652 阶乘0的数量 V2
    51nod 1103 N的倍数
    51nod 2489 小b和灯泡
    51nod 1003 阶乘后面0的数量
    51nod 2122 分解质因数
    javascript中的setter和getter
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/3240775.html
Copyright © 2020-2023  润新知