5

Let's say I have a small program like:

int main() 
{
    cout << "Please enter the param >" << endl; // <-- Print only if input from console
    std::string param;
    cin >> param;
    //Doing some calculations...
    cout << "result is..."
} 

I want to print the request for the parameter only if the input is from the console, but if the program was started with redirect myApp.exe < textfile.txt then I see no point in printing it.

How can I achieve this behavior?

Edit - I'm working on windows.

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • I guess if you use let's say `scanf()`, you won't have this problem or would you? – khajvah Dec 25 '13 at 11:12
  • 2
    Since you're on Windows, you might be able to use [`_isatty`](http://msdn.microsoft.com/en-us/library/f4s0ddew.aspx). – Some programmer dude Dec 25 '13 at 11:13
  • @khajvah - no, `scanf()` will result in the same behavior. ): – Roee Gavirel Dec 25 '13 at 12:10
  • @JoachimPileborg - If you write it as an answer I'll accept it (: – Roee Gavirel Dec 25 '13 at 12:26
  • You can avoid taking a dependency on the CRT with GetStdHandle() and GetFileType(), shown in [this answer](http://stackoverflow.com/a/3453272/17034). – Hans Passant Dec 25 '13 at 13:33
  • I can't comment [Roee Gavirel's answer](http://stackoverflow.com/a/20772730/2665887) because of <50 reputation, so I'm writing my comment as an answer. `_isatty` has some pecularities, as described, for example, [here](http://alfps.wordpress.com/2011/12/08/unicode-part-2-utf-8-stream-mode/#utf8_mode_input_fixed). So, it is better to use [GetConsoleMode](http://msdn.microsoft.com/en-us/library/windows/desktop/ms683167(v=vs.85).aspx) instead of it. In particular, GetConsoleMode is used to detect console in Microsoft C Runtime Library's internals. – user2665887 Dec 25 '13 at 13:17

2 Answers2

3

This answer is based on @JoachimPileborg comment

#include <io.h>
#include <stdio.h>
bool isInputRedirected()
{
    return (!(_isatty(_fileno(stdin))))
}

Original source in MSDN

Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
1

The technical means of detecting redirection depends on the operating system: the C++ standard library has no functionality for that, and AFAIK (though I could be mistaken) neither have Boost.


The best you can do portably is to provide ways for the program invoker to tell it whether it should offer an interactive interface, passing the responsibility to the part that knows enough to take it on.

For examnple, you can use program arguments, and/or you can structure the main functionality as a library invoked from two different front-end programs.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331