gpt4 book ai didi

c++ - 如何保存和恢复 std::istringstream 的缓冲区?

转载 作者:太空狗 更新时间:2023-10-29 20:58:52 25 4
gpt4 key购买 nike

我正在使用 istringstream 逐字读取 string。但是,当我的条件失败时,我需要能够将 istringstream 恢复到读取前一个单词之前。我的示例代码有效,但我想知道是否有更直接的方法来使用流来完成此操作。

std::string str("my string");
std::istringstream iss(str);

std::ostringstream ossBackup << iss.rdbuf(); // Writes contents of buffer and in the process changes the buffer
std::string strBackup(ossBackup.str()); // Buffer has been saved as string

iss.str(strBackup); // Use string to restore iss's buffer
iss.clear(); // Clear error states
iss >> word; // Now that I have a backup read the 1st word ("my" was read)

// Revert the `istringstream` to before the previous word was read.
iss.str(strBackup); // Restore iss to before last word was read
iss.clear(); // Clear error states
iss >> word; // "my" was read again

最佳答案

如果您愿意,您可以使用tellg()seekg() 来保存和恢复您的位置:

#include <string>
#include <sstream>

int main()
{
std::istringstream iss("some text");

std::string word;

// save the position
std::streampos pos = iss.tellg();

// read a word
if(iss >> word)
std::cout << word << '\n';

iss.clear(); // clear eof or other errors
iss.seekg(pos); // move to saved position

while(iss >> word)
std::cout << word << '\n';

}

关于c++ - 如何保存和恢复 std::istringstream 的缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26222332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com