从重定向的标准输入中获取输入时使用seekg() [英] Using seekg() when taking input from redirected stdin

查看:109
本文介绍了从重定向的标准输入中获取输入时使用seekg()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试使用cin.get()两次读取一个字符串。输入被重定向为程序<输入。因此,使用seekg()是有效的。

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().

正如title所说,我认为我可以使用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.

这是我的尝试:

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
}

第二个while循环什么也没做,所以我显然没有正确使用seekg。有人可以告诉我我做错了什么吗?

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?

感谢您的帮助!

推荐答案

您无法在流/管道上搜索。它们不再继续存在于内存中。假设键盘直接连接到您的程序。您只能使用键盘执行的操作是要求更多输入。它没有历史记录。

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\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";
}

给定:


user @ host:/ tmp> ./a.out

找不到

找不到

user @ host :/ tmp> ./a.out< test.cc

确定

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

这篇关于从重定向的标准输入中获取输入时使用seekg()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆