473,320 Members | 1,695 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

What does getchar return if it reads the "enter"...?

When you type one character and press enter, it prints two values, so it turns out that it does read "enter" from the input buffer. What does getchar actually return on reading enter? Moreover I can't understand why fflush(stdin) doesn't have any effect on the output when you type a string like("bytes")and then press enter.

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. /* count characters in input; 2nd version */
  3. void main()
  4. {
  5. int  nc;
  6. for (nc = 0;getchar()!=EOF;nc++)
  7. {
  8. //fflush(stdin);
  9. printf("%d\n",nc);
  10.  
  11.  
  12. //printf("%.0f\n", nc);
  13. }
Jan 21 '11 #1

✓ answered by horace1

the ENTER key is a valid ASCII code and is read by getchar(). Try the following fragment of code and you will see its ASCII value
Expand|Select|Wrap|Line Numbers
  1. int nc;
  2. char ch;
  3. for (nc = 0;(ch=getchar())!=EOF;nc++)
  4. {
  5. printf("%d %d\n",nc, ch);
  6.  
the fflush() function operates when you have writen and wish to write the information to the file, for a detailed explaination see
http://www.cplusplus.com/reference/c...cstdio/fflush/

21 9809
horace1
1,510 Expert 1GB
the ENTER key is a valid ASCII code and is read by getchar(). Try the following fragment of code and you will see its ASCII value
Expand|Select|Wrap|Line Numbers
  1. int nc;
  2. char ch;
  3. for (nc = 0;(ch=getchar())!=EOF;nc++)
  4. {
  5. printf("%d %d\n",nc, ch);
  6.  
the fflush() function operates when you have writen and wish to write the information to the file, for a detailed explaination see
http://www.cplusplus.com/reference/c...cstdio/fflush/
Jan 21 '11 #2
Banfa
9,065 Expert Mod 8TB
getchar returns int and EOF is an int constant. You should not cast the return value of getchar to char, either explicitly or implicitly (by for example assigning it to a variable of type char) before comparing it to EOF.

read this
Jan 21 '11 #3
@banfa i dont think there is any problem in casting the return value of getchar,,,first of all getchar returns unsigned int,not just any int(yeah it returns negative value in case of end of file..)moreove in case of character to integrs type conversion,there is never of problem ...u can always cast a character to integer and integer to a character.....
Jan 21 '11 #4
weaknessforcats
9,208 Expert Mod 8TB
there is never of problem ...u can always cast a character to integer and integer to a character.....
This is not true. An int is bigger than a char so a large value in an int won't fit in the char. While the compiler will let you do the cast, the result is indeterminate and it is up to you to know if the value in the char is correct.
Jan 22 '11 #5
yeah u r right...char range from -128 to 127..its okay but in the question getchar() returns unsigned integer value of characters only..so there should be no problem in casting.....
Jan 22 '11 #6
donbock
2,426 Expert 2GB
Banfa's point was that you need to compare the getchar return value to EOF before you cast the return value to char. That's because the integer code for EOF is guaranteed to not fit in a plain char; thus casting EOF to char will corrupt the value.

It is true that any value returned by getchar other than EOF can indeed be cast to char without corrupting the value.
Jan 22 '11 #7
@donbock but eof=-1,and even char can be negative,,then howcome,,,casting is wrong..........
Jan 22 '11 #8
donbock
2,426 Expert 2GB
I don't know about C++, but the C Standard requires that EOF "expands to an integer constant expression, with type int and a negative value". It may commonly be -1, but there is no requirement that it be that particular negative integer.

The getchar function either returns a character from the input stream or EOF. If EOF had the same value as a valid character then that particular valid character would always be mistaken for EOF. Thus, the value of EOF must be outside the range of the valid characters. I suspect you will find that plain char is unsigned in implementations where EOF is -1; and that EOF has some other negative value in implementations where plain char is signed.
Jan 22 '11 #9
horace1
1,510 Expert 1GB
EOF is system dependent so long as it is not equal to any of the valid character codes (but is commonly -1)
Jan 22 '11 #10
okay i got it what you are trying to say is that,there is no character corresponding,..to eof.....so we cant compare a character to eof..hmmm,but when eof is -1 and char range from -128 to +127 ,,then there has to be some character corresponding to -1 no...
Jan 22 '11 #11
donbock
2,426 Expert 2GB
My point was that I don't believe your combination ("eof is -1 and char range from -128 to +127") is possible. As I said above, "I suspect you will find that plain char is unsigned in implementations where EOF is -1; and that EOF has some other negative value [not -1] in implementations where plain char is signed".
Jan 22 '11 #12
Banfa
9,065 Expert Mod 8TB
No we are not saying there is no character corresponding to EOF (when EOF is -1 and char is signed).

We are saying the reverse that there is a character that corresponds to EOF if you have truncated it to char so if that character appears in the stream you will get a premature and false positive on the comparison to EOF.

Alternatively if char is unsigned when you truncate the returned EOF value to char and the re-extended to compare to EOF there is no sign extension of the unsigned value and you compare 255 to -1 resulting in the stream IO operation not ending even though EOF has been read.

Try reading the page I linked to.

The point is that EOF is explicitly of type int to place it outside the range of values that can be represented with a char (an int having normally at least 8 more bits than a char). For robust and portable code that will work into the future you need to compare to EOF while the type is still an int and only after you are sure it is not EOF convert to a char.
Jan 23 '11 #13
thanking bonfa and donback for your replies,i think i have got it..you are saying that:-
if char is unsigned then comparison of ch with eof(always negative)....will nver cause the loop to end...and if eof is within a valid character range,then...some character will be mistakenly taken as
eof......did i get it right now... :)
Jan 23 '11 #14
Banfa
9,065 Expert Mod 8TB
Yes .
Jan 23 '11 #15
hey people, i wanted to ask,if i type a line and then press enter,how come getchar() is still able to read all the characters of a line..if it only reads a character after pressing enter....It appears as if its reading line by line ,not character by character....please help me out with this confusion....
Jan 25 '11 #16
horace1
1,510 Expert 1GB
Text streams such as stdin operate on a line by line basis with characters entered being placed in an input buffer until newline (or end of file) is entered. Then successive calls to getchar() read characters until the input buffer is exhausted (last character is newline or EOF).
Some C systems have functions which will read individual character by character directly from the keyboard, e.g. function getch() and getche() in <conio.h> in some Windows based compilers. Their use is not recommended as it is non standard and code is not protable.
Jan 25 '11 #17
what if we suffix the input string with ctrl+z on a windows os(an EOF character).and then press enter....in that case getchar() should read eof as well and comeout of the loop no...
Jan 25 '11 #18
horace1
1,510 Expert 1GB
Try the following fragment of code
Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.   int ch=0;
  4.   while(ch != EOF)
  5.   {
  6.    ch=getchar();
  7.    printf(" char %c %d",ch, ch);
  8.   }
  9. }
  10. }
if you enter a line of test is displays the character and the character code.
To enter EOF you enter CTRL/Z then RETURN key on a line by itself and it will break out of the loop. Using CodeBlock under Windows if I type characters then CTRL/Z then RETURN it passes the CTRL/Z as character code 26 decimal not EOF (which is -1 with this compiler)
Jan 25 '11 #19
ok,that means with characters ctrl+z has ascii value 26 and when
provided alone getchar returns unsigned form of -1...(on this
compiler)...but enter is also there in the buffer then why does it not
print enter's ascii value which is 10.....
Jan 25 '11 #20
horace1
1,510 Expert 1GB
the ASCII character code 10 decimal is displayed for RETURN key, e.g. if I type
abc<return>
abc<CTRL/Z><RETURN>
<CTRL/Z><RETURN>
I get
Expand|Select|Wrap|Line Numbers
  1.  char a 97 char b 98 char c 99 char 
  2.  10 char a 97 char b 98 char c 99 char  26 char ÿ -1
  3.  
you can see the character 10 ecimal at the end of the first line. Entering <CTRL/Z> at the end of a line of text displays character code 26 decimal, and EOF appears as -1 decimal.
Jan 26 '11 #21
donbock
2,426 Expert 2GB
You shouldn't count on the ENTER key being encoded as ASCII character 10. Instead, test for the newline character: '\n'. Using the newline character will automatically account for environments with differing end-of-line codes.
Jan 26 '11 #22

Sign in to post your reply or Sign up for a free account.

Similar topics

8
by: EBG | last post by:
I have a simple email form on my site but getting screwy results because I know alot of users are hitting "enter" instead of tab when doing the form. When they hit enter the entire form is...
4
by: Simon Wigzell | last post by:
Is there a way to prevent a form submitting when you press enter on a text field? Some people press enter when they finish typing in a text field out of habit I guess unconcsciously thinking it...
1
by: Byron McClain | last post by:
.... is being consumed. I added an event handler for the "keypress" event and my delegate never gets executed. Why? I am trying to catch the "enter" key pressed event to prevent the DataGrid...
2
by: Cindy | last post by:
Hi all you smarties out there, I'm having a little conundrum with my asp.net page Scenario: I have a form (asp.net) with no code behind (as yet). I have placed a javascript function on a...
1
by: Andrea Williams | last post by:
I've created a simple search form and a submit button. On click of the button, I have code-behind that runs and fills a datagrid. However, it the person is focused on one of the other controls...
7
by: Doug Bell | last post by:
Hi, I have just built a small application with a form that has one Text Box and one Check Box and a couple of Command Buttons. What I am trying to achieve is that if the Text Box has focus and...
2
by: Hoss | last post by:
Hi guys, The framework of my page is an aspx page with a header and a footer. The header is a menu system and depending on what you select there different ascx pages are loaded into the middle...
3
by: aryayudhi | last post by:
I have a html page that has javascript that works perfectly in IE, but not in Firefox. The use of this javascript to change "Tab" to "Enter" Button. When we press Tab, it is like when we press Enter...
1
by: pippyn | last post by:
I'm programming for a CE device with reduced key board, no mouse, and no touch screen. As such, I have to tab from button to button to get the focus on the button i want. Then to invoke the button...
2
by: Magnus Warker | last post by:
Hi, can I associate the pressing of "enter" with one of the forms submit buttons? Thanks Magnus
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.