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 ;)
这篇关于如何重用字符串流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何重用字符串流
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- c++ STL设置差异 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
