Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting string to 'cin'

Tags:

c++

iostream

I have a function that reads user input from std::cin, and I want to write a unittest that inserts some strings into std::cin, such that later extraction from std::cin will read that string instead of pausing for keyboard input.

Ideally, I would change the function signature so that I can pass a custom istream as parameters, but I can't do that here since I have a fixed interface that I cannot change.

cin.putback() is almost what I wanted, however it is inserting only one character at a time, and it is inserting them in reverse order (but I read somewhere that putting back char that wasn't originally there can be dangerous, though the website doesn't elaborate why). I've tried several methods to inject the string to cin's internal buffer cin.rdbuf(), but none would work either. I've also considered using an external testing script or creating subprocess, however I'd like to first consider a test in pure C++.

So, is there any method to put strings into cin? Or do you know a better way to inject my "fake keyboard input"?

like image 667
Lie Ryan Avatar asked Sep 26 '10 09:09

Lie Ryan


People also ask

Can I CIN a string?

Inputting a stringYou can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space.

Can we input string using cin in C++?

The cin object in C++ is an object of class iostream. It is used to accept the input from the standard input device i.e. keyboard. It is associated with the standard C input stream stdin. The extraction operator(>>) is used along with the object cin for reading inputs.

How do I write to Cin?

Cin is used with the extraction operator, which is written as >> (two "greater than" signs). The operator is then followed by a variable where the inputted data is stored. The line must end with a semicolon. Write the cin statement.

Does CIN read new line?

getline(cin, newString); begins immediately reading and collecting characters into newString and continues until a newline character is encountered. The newline character is read but not stored in newString.


1 Answers

Instead of screwing around with cin, you can have your program accept a general std::istream&. When running normally, just pass it cin. During a unit test, pass it an I/O stream of your own creation.

like image 134
Reinderien Avatar answered Sep 28 '22 00:09

Reinderien