Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/128.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ basic_istream::seekg()似乎不起作用_C++_Istream - Fatal编程技术网

C++ basic_istream::seekg()似乎不起作用

C++ basic_istream::seekg()似乎不起作用,c++,istream,C++,Istream,以下程序应输出如下内容: Begin found space found End found 但事实并非如此 #include <sstream> #include <istream> #include <string> #include <cctype> #include <iostream> bool Match(std::istream& stream, const std::string& str) {

以下程序应输出如下内容:

Begin found
space found
End found
但事实并非如此

#include <sstream>
#include <istream>
#include <string>
#include <cctype>
#include <iostream>

bool Match(std::istream& stream, const std::string& str)
{
    std::istream::pos_type cursorPos = stream.tellg();

    std::string readStr(str.size(),'\0');

    stream.read(&readStr[0],str.size());
    stream.seekg(cursorPos);
    if(std::size_t(stream.gcount()) < str.size() || readStr != str)
        return false;

    return true;
}

bool Take(std::istream& stream, const std::string& str)
{
    if(!Match(stream,str))
        return false;

    for(std::string::size_type i = 0; i < str.size(); ++i)
        stream.get();

    return true;
}

int main()
{
    std::string testFile = "BEGIN END";

    std::stringstream ss(testFile);
    auto c = ss.peek();
    while(!ss.eof() && ss.tellg() != -1)
    {
        if(Take(ss,"BEGIN"))
            std::cout << "Begin found" << std::endl;
        else if(Take(ss,"END"))
            std::cout << "End found" << std::endl;
        else if(std::isspace(c))
        {
            ss.get();
            std::cout << "space found" << std::endl;
        }
        else
            std::cout << "Something else found" << std::endl;
    }

    return 0;
}
当我逐步使用调试器时,当我使用空格字符时,它首先检查是否有匹配开始,然后通过tellg检索光标位置,tellg的值为5。但当它预期失败,然后检查是否与END匹配时,光标位于-1,即END


因此,seekg调用似乎不起作用,或者我没有正确使用它。

当程序进入主循环时,它首先使用输入流执行take,并以参数开始。Match返回true,调用get的次数是BEGIN的5倍

然后它再次通过循环。它再次调用匹配。此时,位置为5,即开始的长度。它尝试读取lenBEGIN字符,但您的stringstream没有那么多字符,因此它将循环保留在位置-1,并设置一个错误标志

因为流是错误状态,所以下面的seekg调用没有预期的效果,它解释了程序的行为

Begin found
Something else found