c++ - 如何重用字符串流

标签 c++ file parsing text 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("") 之后,您没有 clear() 流。再看看this answer ,它还解释了为什么应该使用 str(std::string()) 进行重置。在您的情况下,您也可以仅使用 str(szLine) 重置内容。

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

关于c++ - 如何重用字符串流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12112259/

相关文章:

c++ - C++17 静态内联成员的编译器错误

c++ - 不正确的 printf 格式说明符编译

c# - 我们可以从filestream中获取文件的创建时间和日期吗?

jquery - 如何使用jquery发送文件输入?

java - 如何检查字符串是否为正数

javascript - 使用 Javascript 和 HTML 读取和处理 XML

c - C语言解析字符串的意外结果

c++ - 将 vector (在结构中定义时)传递给函数

c - 列表未正确使用正则表达式管理的字符串

c++ - 在游戏编程中,导致性能消耗的特定 C++ 或 STL 功能是什么?