0

I am programming a calculator that uses redirection (UNIX) ./calculator < expressions.txt to receive expressions from a file using a while loop in my main:

while(getline(cin, exp) ) { 
   try { 
     return the evaluated expressions
 }
catch ( error ) { ... }
}

this works fine for me and returns the correct values. However, I also want my program to take in user input if a file is not redirected (It currently error outs and core dumps). How can I take in user input if a file is not provided and avoid the while loop.

Thank you.

1
  • Your file is substituting for stdin. If you execute the command just by itself, you will type ./calculator and then, provide the expression on next line. You can terminate the expression by ctrl-D. Did you mean that you are trying to provide the filename as a command line parameter, such as ./calculator expressions.txt? Commented Mar 2, 2014 at 20:39

2 Answers 2

2

Rather than redirecting stdin why don't you just set up your program to accept command line arguments, one of which could be the file name. Then

int main(int argc, char* argv[]) { 
   if(argc > 1)
   {
      // File name is provided. Open the file and read the data
   }
   else
   {
      // File name is not provided. Get input from user.
   }
   return 0; 
}

This is a bit trivial, but I'm sure you understand the point. For any more complex command line arg parsing, use a library.

Sign up to request clarification or add additional context in comments.

1 Comment

This is a great idea! Thank you very much.
0

When you are taking input from while like this:

./calculator < expressions.txt

It means you are taking input from STDIN only . So if user does not provide input file, the code will itself take input from user only. So you need not to handle file separately in your code. Just take input from stdin.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.