如何重用stringstream

Ice*_*000 17 c++ parsing text file stringstream

这些线程不回答我:

重置字符串流

你如何清除stringstream变量?

        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;
Run Code Online (Sandbox Code Playgroud)

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

回答后的新代码:

...
            szBuffer.str(szLine);
            szBuffer.clear();
            szBuffer>>szKeyWord;
...
Run Code Online (Sandbox Code Playgroud)

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

        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;
Run Code Online (Sandbox Code Playgroud)

Mar*_*mer 27

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

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

  • 这实际上并不可靠.您还需要将任何格式标志重置为默认值.包括你不了解的那些,因为它们是通过调用你背后的`std :: ios_base :: xalloc()`来分配的. (3认同)

Jam*_*nze 8

这取决于你正在做什么.通常更容易创建一个新的istringstreamostringstream.要"重置"一个流,你必须清除它的缓冲区,清除任何错误标志,重置任何格式化标志,加上精度和填充,imbue用原始语言环境重新设置,并且不要忘记使用从返回的值生成的任何扩展格式信息.xalloc.总之,不可能得到正确的.

虽然我在它,你的循环是错误的,并可能导致最后一行被处理两次. file.eof()输入失败后才有可用的含义(即使这样,它也不是100%可靠).你想要的是:

std::string line;
while ( std::getline( file, line ) ) {
    if ( !line.empty() ) {
        std::istringstream buffer( line );
        //  ...
    }
}
Run Code Online (Sandbox Code Playgroud)

(实际上,您可能希望在测试之前从行中修剪尾随空格.)

  • 我喜欢那里有很多资源以一种有组织且有文档记录的方式解释所有那些非常明显的标准信息,而不是 (4认同)
  • 我可以发誓,视频中有一位委员会成员声称人们在使用流时表现不佳,因为他们通过在循环中重新创建流而不是重复使用对流的引用来错误地使用流。我觉得我的生活是一个谎言。 (2认同)