Reputation: 165
For an assignment, part of my program requires that I can receive 2 numbers from either a file or have them entered by hand. I can easily get them from a file by doing:
int n1,n2;
cin>>n1>>n2;
That way, a file with contents simply reading something like "7 13" will have the numbers read in just fine. However, my teacher wants us to have a format where we have a prompt before each number is entered, something that is handled like this:
int n1,n2;
cout<<"Number 1: ";
cin>>n1;
cout<<"Number 2: ";
cin>>n2;
However, using this code eliminates the ability to simply read the 2 numbers in from the file. How can I make it so that both methods work? I can't just combine them into one program because then I would have 2 of the same prompt. Is this even possible?
On a sidenote, I am having the numbers read in by typing on the command line: prog.exe < numberfile >
Upvotes: 0
Views: 247
Reputation: 670
If you really want to use the same code for both streams, than I would suggest:
int n1, n2;
istream* in = NULL;
if (argc > 1) {
in = new ifstream();
in->open(argv[1]);
}
else {
in = &cin;
}
(*in) >> n1 >> n2;
if (argc > 1) {
delete in;
}
cheers,
Upvotes: 1
Reputation: 66459
You can combine them like this:
int n1, n2;
if (argc > 1)
{
std::ifstream input(argv[1]);
if (input)
{
input >> n1 >> n2;
}
else
{
// Handle error
}
}
else
{
// Prompt and read from stdin
}
Upvotes: 0
Reputation: 65
I don't think cout should affect cin, try adding endl at the end of each line maybe that'll be a simple fix.
Upvotes: 0
Reputation: 642
Could do something like this:
int n1,n2,method;
cout << "Enter 1 for file method or 2 for prompts: ";
cin >> method;
if(method == 1)
{
cin >> n1 >> n2;
}
else if(method == 2)
{
cout << "Number 1: ";
cin >> n1;
cout << "Number 2: ";
cin >> n2;
}
Upvotes: 0
Reputation: 56549
cin>>n1>>n2;
...
cin>>n1;
cin>>n2;
They are the same. Printing out stuffs by cout
doesn't affect cin
.
Operator >>
reutrn a reference to a ostream
(cin
in this case) and you can use >>
in a chain.
Upvotes: 1