简体   繁体   English

从std :: cin TWICE读取输入

[英]Reading input from std::cin TWICE

As I take input from cin using the cin.get function, it will automatically update the read location from the input file. 当我使用cin.get函数从cin获取输入时,它将自动更新输入文件中的读取位置。 What should I do to return the read location to the beginning of the file, so that I can take in the input a second time? 我该怎么做才能将读取位置返回到文件的开头,以便我可以再次接收输入?

Say for instance I have the following file input.txt : 比方说我有以下文件input.txt

"Say hello to your new world" “向你的新世界问好”

and the following get loop to take in the input.txt file: 以及以下get循环来获取input.txt文件:

while(cin.get(charTemp)){
     numberOfChars++; 
} 

How could I take in the input twice? 我怎么能接受两次输入?

You won't be able to reread the standard input stream. 您将无法重读标准输入流。 If you really need to read the content twice you'll have to store it, eg: 如果你真的需要两次阅读内容,你必须存储它,例如:

std::stringstream input;
input << std::cin.rdbuf();
input.seekg(0);
// use input and seek back to the beginning if needed

use rewind(stdin) 使用rewind(stdin)

http://www.cplusplus.com/reference/cstdio/rewind/ for reference. http://www.cplusplus.com/reference/cstdio/rewind/供参考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM