Why is my professor using two getchar () ;?

Why is my professor using two getchar (); at the end of our C tutorials?

And what is the “best way” to do this?

+6
c
source share
11 answers

It’s best not to add code to try to open the console window: start your program directly from the console window.

If you must run your program from the IDE and want the program to not be interrupted before the user presses Enter, one single getchar() must do this.

The second best way to make a program terminated after a user presses a key is to always monitor for missing inputs and use one single getchar() .

The reason your teacher uses 2 getchar() , in my opinion, is because there is already a character from the previous inputs in the input buffer. To consume all characters from inputs, up to and including ENTER, this is usually:

 int ch; /* ... */ printf("Press Enter"); fflush(stdout); while ((ch = getchar()) != '\n' && ch != EOF) /* void */; 
+15
source share

It waits for user input so that you can see the result in the program, otherwise it will simply end and the output will not be visible (depending on the OS). Pull it out and try.

+23
source share

He wants the console to remain open and wait for the user to press a key. I think I remember that depending on what happens in your teacher program, above is "getchar ()". There might be something in the buffer, so he added a second "getchar ()". Not exactly the most elegant way to solve a problem.

Edit: Here is a small example. The buffer still has "\ n" from "scanf ()". If you add a second "getchar ()", you will get the expected result. You must flush the buffer to "getchar ()".

 #include <stdio.h> main() { int input; scanf("%d", &input); printf("The input is %d\n", input); getchar(); return 0; } 

Edit 2: Here is the solution taken from here .

 int c; printf( "Press ENTER to continue... " ); fflush( stdout ); do c = getchar(); while ((c != '\n') && (c != EOF)); 
+16
source share

The reason many newbies find it necessary to put two getch in their code is because one single call often does not work.

The reason for this is that getch selects the next keyboard input from the input queue. Unfortunately, this queue is filled whenever the user presses the keys on the keyboard, even if the application does not wait for input at that moment (if he does not read the entire input - see the Lulus example for an example). As a result, getch will select a character from the input queue, without waiting for the next keystroke - what the programmer really wants.

Of course, this “solution” will continue to fail in many cases where there are more than one character in the queue for the keyboard. The best solution is to clear this queue and then request the next character. Unfortunately, I don't have a platform-independent way to do this in C / C ++. The usual way to do this in C ++ (sorry, my C is limited) is as follows:

 std::cin.ignore(std::cin.rdbuf()->in_avail()); 

It simply ignores all available input, effectively clearing the input queue. Unfortunately, this code does not always work, either (for very mysterious reasons).

+5
source share

Why is my professor using two getchar (); at the end of our C tutorials?

Assuming you have something like

 int main ( void ) { int input; scanf ( "%d", &input ); printf ( "The input is %d.\n", input ); getchar(); getchar(); return 0; } 

Two, because scanf will not be returned until the enter key is pressed, but any other characters entered in the input buffer will be entered from the input and \ n \.

So, if you run above and enter 1234 Enter , the program will stop after printing The input is 1234. until you press Enter again. The first getchar reads '\n' associated with the first Enter . If you enter something else, for example 1234 Space Enter , the program does not pause, since the first getchar will read the space. Two getchar may be insufficient, and you have entered the code to print the response in the code to process the input.

And what is the “best way” to do this?

There are various standard ways to read input in C. There are also platform-specific ways to ignore text in the input buffer, but you do not need to do this if you use fgets to read an input line instead of from scanf to read input from the last input line.

fgets (reading input to '\ n' or the end of the file), followed by sscanf (parsing the line for input), is safe from buffer overflows and will absorb any additional input and line ending '\ n'

 #include <stdio.h> int main ( void ) { int input; char buf[16] = ""; fgets ( buf, sizeof buf, stdin ); sscanf ( buf, "%d", &input ); printf ( "The input is %d.\n", input ); fflush ( stdout ); getchar(); return 0; } 

Clearing stdout after printf usually not required for the IO terminal, but it can be if you connect it to the disk (usually, when you register an emergency program, it will lose the most interesting bit before the failure, if you have not cut it).

Since fgets reads and includes the end of the line, there are no characters in the buffer, so you only need one getchar and a bit inconvenient input, for example 1234 Space Enter does not end the program without pausing.

However, most of the time you do not need to wait after starting the console application - on Linux or other Unix systems, the console usually opens and the program starts there, after which control returns to the shell. On the Windows IDE, such as Visual Studio, they usually start the program and pause it using something like:

  "C:\WINDOWS\system32\cmd.exe" /c ""...\ConsoleApplication1.exe" & pause" 

Either you can open cmd.exe and run it there, or you can run it using the .pif shortcut and check the box so that it does not close the console when exiting, or you can create a batch file that starts it and pauses.

You really only need to pause the program if you are running Windows and you use the debugger to start it and you have not set breakpoints.

+5
source share

to pause (possibly) the command line program. he uses two because using only one did not work, and he probably does not know why ..

find him the best solution for this (and not std :: cin), and you will become the hero of the day.

+3
source share

It is possible that the output window opens when the program starts from the IDE.

... why there are two besides me.

+1
source share

This is a naive solution to the problem of unused buffered input. Your professional recognizes the problem, but does not seem to know how to solve it correctly.

If you use formatted input, only the entered characters that match the format specifier are used. So, if, for example, the last input requested a decimal integer using% d, you can enter it into the console:

123<newline>

A formatted input will consume "123", leaving a <newline> buffer. Unformatted input, such as getchar (), will consume it and return immediately. Since this is not what you want, your professor used "just add another getchar () kludge". This only works if the user enters the expected input. A typical waitress machine can print:

123w<newline>

Now the first getchar () gets 'w', the second gets <newline> , and your program exits before you plan it, and in the GUI environment, if the final process belongs to the window in which it is running, then the OS closes it.

A more robust solution is to call getchar () again until <newline> is found:

 while( getchar() != '\n' ) { /*do nothing*/} ; getchar() ; /* wait */ 

Of course, if the previous input was a character, you need to check that it was not <newline> yet:

 while( ch != '\n' && getchar() != '\n' ) { /*do nothing*/} ; getchar() ; /* wait */ 

Instead of putting the flash loop at the end immediately before the input call "wait", it is better to flush the buffer after each required input. This is because it is there that you know that you need it and how it should be encoded. I prefer to write wrapper functions for the input types that I need.

+1
source share

getchar(); at the end of the program, the situation “Press any key to continue” is created. I guess he likes to hit any key twice.

0
source share

To extract the remaining "\ n" from the buffer so that the application closes.

0
source share

Since a single press of the enter button generates two characters on Windows, see wikipedia . At least it has been used for too long in a distant galaxy ...

-3
source share

All Articles