Saturday, May 22, 2010

C's equivalent to C++'s getchar()?

I am learning C and I do not know how to make the program end when the user presses the Enter Key. How is this done? I know the basics of C++ and it's getchar(), I tried it in C hoping to get lucky...didn't work.

C's equivalent to C++'s getchar()?
bro use getch(); instead of getchar();
Reply:getchar() is actually a C function that C++ inherited. If it is not doing what you want, it's probably because you haven't processed the last '\n' in the standard input.





My recommendation is to do all your input processing line by line (using std::getline in C++, and fgets in C). That way there's never a question of whether you have processed the end of line or not.
Reply:First of all, it depends on your compiler, by default Visual Studio (from MS) and the GNU C Comiler GCC do that for you.





Borland made a header file called "conio.h" that uses a function called getch(); that does the very same thing that you intend on the question. But beware, that code won't be very portable.








By the way, if you need a equivalent to getch(); some people did a equivalent function on the web that you can download; and yes IT WILL BE PORTABLE.





Finally, if your'e in a hurry and can't waste more time looking for another function, you can try a simple cin %26gt;%26gt; "expression"; and finish the program. It's not nice, but it works.
Reply:Include this header file:


#include %26lt;conio.h%26gt;





//Don't know if it works in C as well. However, it does work


//in C++.





//Then use the following function to check the entered


//character.





char check;





check = getch();





//You said getchar();
Reply:use getch();





and if u havent said void main(); then return 0;





also remember 2 include %26lt;conio.h%26gt;


No comments:

Post a Comment