As terdon pointed out already, to do this you want to either redirect stdin
from a file (and call the program using e.g. program <inputfile.txt
) or change your program so that it parses arguments passed from the command line (and call the program using e.g. program 1 2
);
In the first case you want to suppress the first two cout
s if stdin
is not connected to a terminal, and in the second case you want to suppress the first two cout
s, e.g., if, say, not enough arguments have been passed from the command line;
Speaking of the first method, you can check whether a file descriptor is connected to a terminal using the isatty()
function (POSIX function defined in unistd.h
):
int isatty(int fd);
If fd
is an opened file descriptor connected to a terminal, the function will return 1
; If fd
is not an opened file descriptor or is not connected to a terminal, the function will return 0
:
#include <iostream>
#include <unistd.h>
int main() {
int x, y, sum;
std::cout << "A program which adds two integers\n";
if(isatty(0)) {
std::cout << "Enter 1st integer: ";
}
std::cin >> x;
if(isatty(0)) {
std::cout << "Enter 2nd integer: ";
}
std::cin >> y;
sum = x + y;
std::cout << "Sum is " << sum << std::endl;
return 0;
}
This way the user will be prompted to insert the numbers only if stdin
has not been redirected:
user@user-X550CL ~/tmp % ./a.out
A program which adds two integers
Enter 1st integer: 1
Enter 2nd integer: 2
Sum is 3
user@user-X550CL ~/tmp % cat inputfile.txt
3
4
user@user-X550CL ~/tmp % ./a.out <inputfile.txt
A program which adds two integers
Sum is 7
Speaking of the second method, here's a very rough example on how to parse arguments passed from the command line (arguments passed from the command line are stored into argv
, which is an array of pointers to a character, so you'll have to cast each argument to an integer, but don't use atoi()
! Use something that allows you to check if the arguments are numeric or not. I used atoi()
just for the sake of simplicity):
#include <iostream>
#include <cstdlib>
int main(int argc, char *argv[]) {
int x, y, sum;
std::cout << "A program which adds two integers\n";
if(argc == 3) {
x = atoi(argv[1]);
y = atoi(argv[2]);
}
else {
std::cout << "Enter 1st integer: ";
std::cin >> x;
std::cout << "Enter 2nd integer: ";
std::cin >> y;
}
sum = x + y;
std::cout << "Sum is " << sum << std::endl;
return 0;
}
This way the user will be prompted to insert the numbers only if not enough arguments have been passed from the command line:
user@user-X550CL ~/tmp % ./a.out
A program which adds two integers
Enter 1st integer: 1
Enter 2nd integer: 2
Sum is 3
user@user-X550CL ~/tmp % ./a.out 3
A program which adds two integers
Enter 1st integer: ^C
user@user-X550CL ~/tmp % ./a.out 3 4
A program which adds two integers
Sum is 7
isatty
like in stackoverflow.com/a/5157076/592540