Using seekg() when taking input from redirected stdin

后端 未结 4 2040
情话喂你
情话喂你 2020-12-12 04:48

So i\'m trying to read in a string of characters twice using cin.get(). The input is being redirected as \"program < input\". So it is valid to use seekg().

As th

4条回答
  •  攒了一身酷
    2020-12-12 05:29

    You can't seek on streams/pipes. They don't continue to exist in memory. Imagine the keyboard is directly connected to your program. The only operation you can do with a keyboard is ask for more input. It has no history.

    If it's just a keyboard you can't seek, but if it's redirected with < in the shell seeking works fine:

    #include 
    
    int main() {
      std::cin.seekg(1, std::ios::beg);
      if (std::cin.fail()) 
        std::cout << "Failed to seek\n";
      std::cin.seekg(0, std::ios::beg);
      if (std::cin.fail()) 
        std::cout << "Failed to seek\n";
    
      if (!std::cin.fail()) 
        std::cout << "OK\n";
    }
    

    Gave:

    user@host:/tmp > ./a.out
    Failed to seek
    Failed to seek
    user@host:/tmp > ./a.out < test.cc
    OK

提交回复
热议问题