【问题标题】:istringstream not changing c++istringstream 不改变 C++
【发布时间】:2013-08-23 14:31:33
【问题描述】:

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

#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 &gt;&gt; hex &gt;&gt; tempVal; 似乎使用了 tempIss 的旧值!?

谢谢。

【问题讨论】:

  • if( ! (tempIss >> hex >> tempVal)) process_error();否则输出();

标签: c++ istringstream


【解决方案1】:
tempIss.str(tempStr);

这只是设置内部缓冲区的内容。但是,它不会重置之前操作可能在流上设置的错误标志。

在第二次提取之前说 tempIss.clear(); 应该可以完成这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2011-02-15
    • 2013-05-11
    • 1970-01-01
    相关资源
    最近更新 更多