Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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:

"Say hello to your new world"

and the following get loop to take in the input.txt file:

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

How could I take in the input twice?

like image 600
LucianNovo Avatar asked Dec 09 '25 10:12

LucianNovo


1 Answers

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, e.g.:

std::stringstream input;
input << std::cin.rdbuf();
input.seekg(0);
// use input and seek back to the beginning if needed
like image 115
Dietmar Kühl Avatar answered Dec 11 '25 23:12

Dietmar Kühl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!