如何重用stringstream [英] how to reuse stringstream

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

问题描述

这些线程不会回答我:

重置一个stringstream

  std :: ifstream file(szFIleName_p ); 
if(!file)返回false;

//创建一个字符串流来解析

std :: stringstream szBuffer;

std :: string szLine; //当前行
std :: string szKeyWord; //第一个字在行中标识它包含的数据

while(!file.eof()){

//逐行阅读

std :: getline(file,szLine);

//忽略空行

if(szLine ==)continue;

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

szKeyword 将始终包含第一个单词,

新的代码回答:

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

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

  std :: string szLine; //当前行
std :: string szKeyWord; //第一个字在行中标识它包含的数据

//逐行阅读

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

//忽略空行

if(szLine ==)continue;

//创建一个字符串流来解析
$ b $ std :: istringstream szBuffer(szLine);
szBuffer>> szKeyWord;


()调用 str()之后的流。再看看这个答案,它也解释为什么你应该重置使用 str(std :: string())。在你的情况下,你也可以使用 str(szLine)来重置内容。 调用 clear(),流标志(如 eof )不会被重置,导致令人惊讶的行为。 )

These threads do NOT answer me:

resetting a stringstream

How do you clear a stringstream variable?

        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 will always contain the first word, szBuffer is not being reset, can't find a clear example anywhere on how to use stringstream.

New code after answer:

...
            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;

解决方案

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).

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

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

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