1

I'm writing a function that take a date from the user in the form DD/MM/YYYY, I want the user to enter the numbers only and the program print /.

I've wrote a code that show a massage prompt the user to enter the date and store the day , month and year in separate variable.

    int day;
    int month;
    int year;

    cout << "Enter your birthday date:  "
    cin >> day;
    cout << "/";
    cin >> month;
    cout << "/";
    cin >> year;

what I want is when the user enter the day witch is 2 digit number the program automatically move to the next line and print / so the user enter the next input without pressing enter. But the code I have wrote require pressing enter after each input.

Rm R
  • 43
  • 5

2 Answers2

2

It is not your program that requires this: it is your terminal.

By default many terminals are line-buffered — they only send full lines.

You can usually change this in your terminal's settings, but requiring your users to do that is a bit of a drag.

Alternatively, there are some very unportable ways to trick various terminals into doing this autonomously, from within the program. (If you're to go down this route, ncurses is probably the most portable.)

But, ultimately, gaining this sort of flexibility in interaction is what GUIs were invented for, and you might consider switching to that paradigm instead.

Otherwise, if you're sticking with the non-graphical interface, I would recommend just accepting a date in the input stream, in a usual format (e.g. YYYY-MM-DD or DD/MM/YYYY) and parse it as necessary. This will also interact better with scripts and piped-in input; generally when dealing with the command-line you should try to make it so that you are not dependant on a human typing in a character at a time, because that's not how your program sees it!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

The answer is:

There is no standard way to do this. In fact, some libraries (Platform dependent like windows.h / termcap.h or thirdparty like conio.h) allow you to either use the

char getchar(void);

function, or put your terminal (or standard input by extent) in "Raw"/"Canonical" mode, where the character prompt won't wait for the user to press enter key, and report the char right after it was typed, therefore needing to move the read sequence to a loop.

I suggest finding a workaround for this kind of issues, or just put some error check to prevent user from typing stupid data into the field

stalker2106
  • 118
  • 9