I want to write a program to solve a simple guessing game. I’m learning about command line piping and redirects, and so I was wondering if this is even possible.
Basically I want the output of one to be the input of the other, and then the output of that to be the input of the other.
This is all just for fun so I can learn, I know I can change the source code of the guessing game and include the solving algorithm, but just for fun let’s assume I don’t have the source code.
Is this even possible? Here’s my code:
//GuessingGame.cc
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
srand(time(NULL));
int number = rand()%100;
int guess = -1;
int trycount = 0;
while(guess != number && trycount < 8) {
cout << "Please enter a guess: ";
cin >> guess;
if(guess < number)
cout << "Too low" << endl;
else if(guess > number)
cout << "Too high" << endl;
trycount++;
}
if(guess == number)
cout << "You guessed the number!";
else
cout << "Sorry, the number was: " << number;
return 0;
}
Solver.cc
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[]) {
string prompt;
int high = 100;
int low = 0;
int guess = 50;
getline(cin,prompt);
if(prompt == "Please enter a guess: ")
cout << guess;
while(true) {
getline(cin,prompt);
if(prompt == "Too low")
low = guess;
else if(prompt == "Too high")
high = guess;
else if(prompt == "You guessed the number!")
return 0;
guess = (low+high)/2;
cout << guess;
}
}
I hope you understand what I’m doing, and I don’t care so much about the program, it’s just an example. The main question is if you can interact with two different programs, using redirects and piping and such. Thanks
A pipe is by definition a one-way communication device. However it can be solved by using two pipes, one in each direction. The problem is that it can’t be done easily through a shell, you have to make a program to set up the pipes, creates the processes for your programs and then executes them with the pipes set up as the correct input/output channels.
The only way I can think about how to make this possible through a shell, is to use the
mkfifocommand to create two pipes. Start one program in the background with the input and output redirected from/to the correct pipes, and then do the same with the other program but use the other pipe as input and output.