I have to read input according to these rules:
“The input consists of several lines of text. Some lines may be empty. The input can be fed from a file, using a line such as
prog.exe < input.txtin which case the end of input is indicated appropriatelly by the operating system. If you enter input using a keyboard, there is normally a way to signal the end of input with some control key, depending on the operating system (e.g., Ctrl+d in Unix/Linux-style systems, and Ctrl+z in Microsoft systems).”
Previously I have been doing it this way
while(getline(cin, data)) {
if(data == "0") break;
/ * do stuff */
}
So I can read as many lines as I want and preform calculations, and then when I’m done just type a 0 and end my program. I tried entering a list of things in a .txt file one per line, and then calling program.exe < myfile.txt but nothing happened.
What’s this < file.txt doing?
How can I properly handle content inside it when calling my program like that?
And how can I make it calculate things when you hit ctrl+z?
Paraphrasing the text of your exercise:
Using
command1 < file1executescommand1, withfile1as the source of input (as opposed to the keyboard).This is known as redirecting standard input.
std::cinwill get its input fromfile1instead of from the keyboard.The end of the input file is analogous to CTRL+Z (on Microsoft systems, CTRL+D on most others). Once
std::getline()reaches the end of the file (or you read a line with just “0”), you’ll exit yourwhile-loop and then you can do your calculation on thedatayou’ve collected (and presumably stored in some container).