istringstream没有更改c++

istringstream not changing c++

本文关键字:c++ istringstream      更新时间:2023-10-16

我写了一些代码来显示我在另一个程序中转换一些输入字符串时遇到的问题。

#include <iostream>
#include <sstream>
#include <bitset>
using namespace std;
int main()
{
    string        tempStr;
    unsigned long tempVal;
    istringstream tempIss;
    bitset<32>    tempBitset;
    // Input the first word in hex and convert to a bitset
    cout << "enter first word in hex : ";
    cin >> tempStr;
    tempIss.str(tempStr);
    cout << "word2 tempIss : " << tempIss.str() << endl;
    tempIss >> hex >> tempVal;
    cout << "word2 tempVal : " << (int)tempVal << endl;
    tempBitset = tempVal;
    cout << "word1 tempBitset: " << tempBitset.to_string() << endl;
    // Input the second word in hex and convert to a bitset
    cout << "enter second word in hex : ";
    cin >> tempStr;
    tempIss.str(tempStr);
    cout << "word2 tempIss : " << tempIss.str() << endl;
    tempIss >> hex >> tempVal;
    cout << "word2 tempVal : " << (int)tempVal << endl;
    tempBitset = tempVal;
    cout << "word2 tempBitset: " << tempBitset.to_string() << endl;
    return 0;
}

我的问题是,当tempIss的值似乎随着tempIss.str(tempStr);函数的变化而变化时,下面的tempIss >> hex >> tempVal;似乎使用了tempIss!?的旧值!?

谢谢。

tempIss.str(tempStr);

这只是设置了意图缓冲区的内容。但是,它不会重置以前操作中可以在流上设置的错误标志。

在第二次提取之前说tempIss.clear();就可以了。