0

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 >

user1804208
  • 165
  • 2
  • 4
  • 9

5 Answers5

1
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.

masoud
  • 55,379
  • 16
  • 141
  • 208
  • Yes, those are the same, but having text output between the two is not. I get an error message if I try to read in a file with text in the way. – user1804208 Oct 03 '13 at 07:16
1

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,

naazgull
  • 640
  • 1
  • 8
  • 12
0

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;
}
Safinn
  • 622
  • 3
  • 15
  • 26
0

I don't think cout should affect cin, try adding endl at the end of each line maybe that'll be a simple fix.

C T
  • 65
  • 7
0

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
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82