2012-10-16 45 views
2

我写了下面的测试代码:提取操作符(>>)是否可以覆盖变量?

int main(int argc, char* argv[]) { 
    stringstream ss; 
    int num; 

    ss << "54321"; 
    ss >> num; 
    ss.str(""); 
    ss << "12345"; 
    ss >> num; 

    fprintf(stderr, "%d\n", num); 
} 

令我惊讶的是,结果是54321你如何正确使用覆盖提取操作变量(>>)?

回答

8

第一次提取后,您到达流的末尾,因此eofbit已设置,第二次提取失败。

int main(int argc, char* argv[]) { 
    stringstream ss; 
    int num; 

    ss << "54321"; 
    ss >> num; 

    // eofbit was set above, 
    // we need to clear it 
    ss.clear(); 

    ss.str(""); 
    ss << "12345"; 
    ss >> num; 

    fprintf(stderr, "%d\n", num); 
} 

呼叫clear()成员函数试图第二次提取之前。 第二个问题是内部get指针的位置,它不会自动重置。使用 seekg()进行设置。

编辑:striked的东西不是必要的,解释here

+0

谢谢,这解决了我的问题。 –

+0

@SomeNoobStudent不客气。 – jrok

4

当流到达流的末尾时,std::ios_base::eofbit被设置。试图提取任何日期之前,抽出检查是否有任何状态标志设置,如果是这样,它不会做任何事情,你提取失败:

std::stringstream ss; 
ss << "54321"; 
ss >> num; // sets eof: 
std::cout << "eof: " << ss.eof() << "\n"; 

要让流做任何事情,一旦任何国家标志被置位,则需要先清除标志:

ss.clear(); 
ss << "12345"; 
if (ss >> num) { 
    std::cout << "num=" << num << "\n"; 
} 
else { 
    std::cout << "failed to extract a value\n"; 
} 

就个人而言,我一般不使用输出操作符来设置字符串流的内容。相反,我通常使用str()成员:

std::ostringstream out; // note: this is just an output string stream 
... 
out.clear();   // the clear is still needed 
out.str("12345");