簡體   English   中英

從重定向的標准輸入中獲取輸入時使用seekg()

[英]Using seekg() when taking input from redirected stdin

因此,我嘗試使用cin.get()兩次讀取一個字符串。 輸入被重定向為“程序<輸入”。 因此,使用seekg()是有效的。

正如titel所說,我認為我可以使用seekg()保存字符串的起始位置,因此我可以再次使用同一字符串的起始位置。

這是我的嘗試:

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。 有人可以告訴我我做錯了什么嗎?

謝謝你的幫助!

您無法在流/管道上搜索。 它們不再繼續存在於內存中。 假設鍵盤直接連接到您的程序。 您可以使用鍵盤執行的唯一操作是要求更多輸入。 它沒有歷史。

如果只是鍵盤,則無法搜索,但是如果在外殼程序中使用<重定向它,則可以正常運行:

#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

你不能那樣做。 std :: cin通常連接到終端,因此無法進行隨機訪問。

如果您使用的流是std :: istringstream或std :: ifstream,則可以這樣做。

我的建議是將std :: cin中的所有字符讀入一個std :: string中,然后從該字符串中創建一個std :: istringstream,然后在該std :: istringstream而不是std :: cin上嘗試使用您的技術。

您無法在流中搜索。 您必須取消字符。

您不能在流上搜索,但是可以使用std::cin.peek()std::cin.unget()

1)通過使用cin.peek()

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

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

2)通過使用cin.unget()

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

cin.unget();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM