Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
418 views
in Technique[技术] by (71.8m points)

c++ - Using seekg() when taking input from redirected stdin

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 the titel says, I thought I would be able to use seekg() to save the beginning position of the string, so I could come back to use the starting position of the same string again.

Here is my attempt:

char c;
while (cin.get(c))
{
  //do stuff 
}

cin.seekg(0, ios::beg);

while (cin.get(c))
{
  //do stuff with the string a second time
}

The second while loop isn't doing anything, so I'm obviously not using seekg correctly. Could someone tell me what I'm doing incorrectly?

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 <iostream>

int main() {
  std::cin.seekg(1, std::ios::beg);
  if (std::cin.fail()) 
    std::cout << "Failed to seek
";
  std::cin.seekg(0, std::ios::beg);
  if (std::cin.fail()) 
    std::cout << "Failed to seek
";

  if (!std::cin.fail()) 
    std::cout << "OK
";
}

Gave:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...