how to reuse 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;
szKeyword 将始终包含第一个单词,szBuffer 不会被重置.我在任何地方都找不到关于如何使用 stringstream 的明确示例.
szKeyword will always contain the first word, szBuffer is not being reset. I can't find a clear example anywhere on how to use stringstream.
回答后的新代码:
...
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;
推荐答案
您在调用 str("") 后没有 clear() 流.再看看这个答案,它还解释了为什么你应该使用 str(std::string()) 重置.在您的情况下,您还可以仅使用 str(szLine) 重置内容.
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).
如果你不调用clear(),流的标志(如eof)不会被重置,导致令人惊讶的行为;)
If you don't call clear(), the flags of the stream (like eof) wont be reset, resulting in surprising behaviour ;)
这篇关于如何重用字符串流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何重用字符串流
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
