How to catch newlind on Win in getline

Hi, all
How to distinguish difference between stdin and string supplied with “<”.
I care only about Windows platform, so th difference is new line chars "\r\n" , is this the only way to catch what is the case here, checking winBuffer for \r\n ? or there is another way ? I really need to know how string was entered to implement something like:
1
2
3
4
5
6
7
8
9
.....
.....
Cin.getline (WinBuffer, SzBuffer)
....
If WinBuffer has a \r\n         // stdin with ENTER
   Plan A;
Else                           // with "<" redirection
Plan  B;
.....


Sorry I’m bit new to cpp (like 90%:-), so appreciate you help with syntax, my class officially will start in Jan only and I really want knock it down before. Some samples on www I still can’t get.

Tx
M
Last edited on
When on Windows, all newlines are "\r\n", whether from a human or a file.

To determine whether or not you are attached to a human, use GetConsoleMode().
If you are on *nix, use isatty().

Here is some code I wrote a while ago, but haven't yet had the time to post in its own Article:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#ifdef _WIN32

  #define NOMINMAX
  #include <windows.h>

  bool isconsole( unsigned id )
    {
    static DWORD handles[] = {
      STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
      };
    DWORD foo;
    if (id > 2) return false;
    return GetConsoleMode( GetStdHandle( handles[ id ] ), &foo ) != 0;
    }

#else

  #include <unistd.h>

  #ifndef ISATTY
    /* Assume that the standard isatty() is defined */
    #define ISATTY isatty
  #else
    /* The user has defined something unique. Prototype it. */
    int ISATTY( int );
  #endif

  bool isconsole( unsigned id )
    {
    static int filenos[] = { STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO };
    if (id > 2) return false;
    return ISATTY( filenos[ id ] );
    }

  #undef ISATTY

#endif 

The *nix code makes pains to be as portable as possible -- as not all systems provide a sane isatty() implementation -- or they do not prototype it in <unistd.h> -- so we give the user the build option to make things work on their system.

To use it, it is as simple as:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

// Either cut and paste the above code here,
// or put it in its own .cpp and #include a header with a proper prototype,
// or put it in its own .cpp and put a proper prototype here.

int main()
  {
  if (isconsole( 0 )) cout << "Stdin is a human. (Probably.)\n";
  else                cout << "Stdin is a file.\n";
  return 0;
  }

And here's a sample run for you:

D:\prog\cc\foo>a
Stdin is a human

D:\prog\cc\foo>a < a.cpp
Stdin is a file

D:\prog\cc\foo>

Hope this helps.
Hi, Duoas !!!!!

That's really helpes and saves my project !!!

THanks again for Xmas gift.
Best
Mario
Topic archived. No new replies allowed.