如何重用字符串流 [英] how to reuse stringstream

查看:28
本文介绍了如何重用字符串流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些线程不回答我:

重置字符串流

如何清除字符串流变量?

std::ifstream file( szFIleName_p );
if( !file ) return false;

// create a string stream for parsing

std::stringstream szBuffer;

std::string szLine;     // current line
std::string szKeyWord;  // first word on the line identifying what data it contains

while( !file.eof()){

    // read line by line

    std::getline(file, szLine);

    // ignore empty lines

    if(szLine == "") continue;

    szBuffer.str("");
    szBuffer.str(szLine);
    szBuffer>>szKeyWord;

szKeyword 将始终包含第一个单词,szBuffer 不会被重置.我在任何地方都找不到关于如何使用 stringstream 的明确示例.

szKeyword will always contain the first word, szBuffer is not being reset. I can't find a clear example anywhere on how to use stringstream.

回答后的新代码:

...
szBuffer.str(szLine);
szBuffer.clear();
szBuffer>>szKeyWord;
...

好的,这是我的最终版本:

Ok, thats my final version:

std::string szLine;     // current line
std::string szKeyWord;  // first word on the line identifying what data it contains

// read line by line

while( std::getline(file, szLine) ){

    // ignore empty lines

    if(szLine == "") continue;

    // create a string stream for parsing

    std::istringstream szBuffer(szLine);
    szBuffer>>szKeyWord;

推荐答案

您在调用 str("") 后没有 clear() 流.再看看这个答案,它还解释了为什么你应该使用 str(std::string()) 重置.在您的情况下,您还可以仅使用 str(szLine) 重置内容.

You didn't clear() the stream after calling str(""). Take another look at this answer, it also explains why you should reset using str(std::string()). And in your case, you could also reset the contents using only str(szLine).

如果你不调用clear(),流的标志(如eof)不会被重置,导致令人惊讶的行为;)

If you don't call clear(), the flags of the stream (like eof) wont be reset, resulting in surprising behaviour ;)

这篇关于如何重用字符串流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆