Using getchar to keep program running

This is a discussion on Using getchar to keep program running within the C Programming forums, part of the General Programming Boards category; In the beginner tutorial on this site, it mentioned that adding the line getchar(); right before return 0; at the ...

Using getchar to keep program running

In the beginner tutorial on this site, it mentioned that adding the line getchar(); right before return 0; at the end of the main function would keep the program running until the user hit enter.

Well, this works for me on some programs, and not on others, and I really can't see the difference between them. Following is the main function from a program I wrote based off of one of the tutorial examples. Adding getchar(); doesn't keep the program from closing, either in my program or in the tutorial example (which did not have it included, I added it).

Oh, now that I've already posted my entire code, I'm having another issue and I don't quite know how to resolve it. After adding getchar after the scanf in my ask function, it works fine. Another thing that works fine is where I told it to run the ask function again after scolding the user if the age entered is less than 0.

The problem is when I combine the two. If I enter a number less than 0, it runs the ask function again, but then it never prints my message. I think I know why: the ask function is inside the if statement, but the value of the ask function is evaluated outside of it in the main function. How do I get it to re-run my ask function for values less than 0 but still send the age value back to the main function to be evaluated again?

Well thats going to be a bit of work you then, since you will have to return the local variable of ask function to the main back again. There are many ways to resolve that problem. What I would suggest to start with is to bring that scanf statement down to the main function itself.

And that should resolve the problem easily. Or you will have to send variable as an argument to the ask function as a reference parameter and read the value in the function and then use that read value in the main function by dereferencing it. You will have to be familiarized the pointers to do that!