c – 如何重用stringstream

前端之家收集整理的这篇文章主要介绍了c – 如何重用stringstream前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这些线程不回答我:

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将始终包含第一个单词,szBuffer没有被重置,在任何关于如何使用stringstream的任何地方找不到一个明确的例子.

代码回答:

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

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

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(“”)后,您没有清除()流.再看看 this answer,它也解释了为什么你应该使用str(std :: string())重置.而在您的情况下,您也可以仅使用str(szLine)重置内容.

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

原文链接:https://www.f2er.com/c/112428.html

猜你在找的C&C++相关文章