这些帖子不回答我:
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/