473,396 Members | 1,756 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,396 software developers and data experts.

Comprehension problem between getchar() and fgetc().

35
// FIRST
Expand|Select|Wrap|Line Numbers
  1.  
  2. int main(void){
  3. int c, i = 0;
  4. char cArray[100];
  5.  
  6. while( (c = getchar()) != '\n' && c != EOF){
  7.    cArray[i] = c;
  8.    i ++;
  9. }
  10. }
  11.  
// SECOND
Expand|Select|Wrap|Line Numbers
  1. void readRestOfLine(){
  2.  int c;
  3.  
  4.    /* Read until the end of the line or end-of-file. */   
  5.    while ((c = fgetc(stdin)) != '\n' && c != EOF)
  6.       ;
  7.  
  8.  /* Clear the error and end-of-file flags. */
  9.    clearerr(stdin);
  10. }
  11.  
//THIRD
Expand|Select|Wrap|Line Numbers
  1. int main(){
  2.    int c;
  3.  
  4.   c = getchar();
  5.    readRestOfLine();
  6. }
  7.  
I have problem comprehend the blocks of C code above.

The FIRST , getchar() read every single char from STDIN to the buffer first, then store into cArray through c as long as the condition is true in the while loop. In this case, is the '\n' character being read into the buffer? As i knew, it would right ? but it won't be store inside the cArray due to the false condition. wherever the getchar() is invoke, the program would wait for user to enter input. am i correct ?

While the SECOND, the same while loop with the same testing condition, but using fgetc(), why does the program would execute the while loop smoothly without waiting the user to enter some input ? In my understanding, getchar() is the same as fgetc(), am i correct ? And the function is use to clear the buffer? what buffer is that ? is it the STDIN's buffer ? the function use the fgetc() to read the remaining input in the buffer in a empty while loop, so after the remaining data being read into variable c, what is the next ? Is it the variable and value inside c just "dead" after exiting the function? i am not sure. how does it clear the buffer exactly ?

The THIRD, if i type "a" and press '\n' char, the 'a' would go into buffer and store inside c while the '\n' will still remain in buffer , correct ? that's why it would result some weird output , isn't it ? that's is the usage of SECOND function to clear the remaining input in buffer ?

I am new to this website, i found it would certainly help me. If i make any mistake in term of posting regulation , please correct me. Thanks
Aug 21 '07 #1
9 5121
primeSo
35
: ( , no one reply me , i need clarification badly on this issue.
Aug 22 '07 #2
gpraghuram
1,275 Expert 1GB
: ( , no one reply me , i need clarification badly on this issue.
One good practice to follow wile reading from stdin is, flushing it and then reading it.
use fflush(stdin);
This may sole the problem u are facing with the second idea.
I will spend somre time on this and can add to this.

Raghuram
Aug 22 '07 #3
JosAH
11,448 Expert 8TB
One good practice to follow wile reading from stdin is, flushing it and then reading it.
use fflush(stdin);
That is nonsense: you can't flush an input stream. Flushing is something you do
on output streams in case they're buffered. The moment you're attempting to
flush an input stream (if possible), new data may arrive rendering the flushing
useless.

kind regards,

Jos
Aug 22 '07 #4
Banfa
9,065 Expert Mod 8TB
Actually
Expand|Select|Wrap|Line Numbers
  1. fflush(stdin);
  2.  
invokes undefined behaviour, read this
Aug 22 '07 #5
Banfa
9,065 Expert Mod 8TB
In my understanding, getchar() is the same as fgetc(), am i correct ? And the function is use to clear the buffer? what buffer is that ? is it the STDIN's buffer ? the function use the fgetc() to read the remaining input in the buffer in a empty while loop, so after the remaining data being read into variable c, what is the next ? Is it the variable and value inside c just "dead" after exiting the function? i am not sure. how does it clear the buffer exactly ?
A lot of you other questions could easily be answered by simply compiling and running the code (especially stepping through it in a debugger).

getchar() always operates on stdin where as fgetc(...) operates on any (readable) FILE stream. getchar() and fgetc(stdin) are equivalent. Yes the function just clears the stdin input buffer, none of the data is returned by the function.

What you need to be aware of is that when getchar() or fgetc(stdin) are called then program stops and waits for user input and it grabs everything the user types until the newline (or EOF) is encountered when it returns to your program and returns the first character in the buffer. This means that when you call getchar() you receive 1 character but there could be a lot of left over data still in the stdin input buffer.
Aug 22 '07 #6
primeSo
35
A lot of you other questions could easily be answered by simply compiling and running the code (especially stepping through it in a debugger).

getchar() always operates on stdin where as fgetc(...) operates on any (readable) FILE stream. getchar() and fgetc(stdin) are equivalent. Yes the function just clears the stdin input buffer, none of the data is returned by the function.

What you need to be aware of is that when getchar() or fgetc(stdin) are called then program stops and waits for user input and it grabs everything the user types until the newline (or EOF) is encountered when it returns to your program and returns the first character in the buffer. This means that when you call getchar() you receive 1 character but there could be a lot of left over data still in the stdin input buffer.
yes, i am almost there, thanks but
I still feel doubt with the fgetc() in the SECOND block of code. According to your statement, that means the program will stop and waiting the user to input data in the while loop. But in fact, it doesn't. Is it because fgetc() automatically read those left over in the buffer ? The key is lie at the empty statement, isn't it ? that means if i simply place the empty while loop statement after the while loop in the FIRST code, it will clear the buffer as well. Last, is the '\n' would be read in from the stdin to the buffer ? or to the cArray ?
Aug 22 '07 #7
Banfa
9,065 Expert Mod 8TB
yes, i am almost there, thanks but
I still feel doubt with the fgetc() in the SECOND block of code. According to your statement, that means the program will stop and waiting the user to input data in the while loop. But in fact, it doesn't.
This is because you have called it in the context of the THIRD block, that is a call to getchar() has already been made which has put data into the input buffer.

Let me clarify the operation of getchar() and fgetc(stdin)

When these functions are called first the check the input buffer, if there is data available in the buffer then they return the next character in the buffer and move the buffer pointer(indicating which is the next character to return) on 1 character. If there is no data in the buffer then the request input from the user (on screen cursor flashes). All of the users data up to the next return character is stored in the input buffer, this can be anywhere between 1 (if the just press return) character to lots of characters.

So if you call getchar() or fgetc(stdin) twice in a row then, unless the user just presses return, the program will not request data for the second call as there will already be data available in the input buffer.

The key is lie at the empty statement, isn't it ? that means if i simply place the empty while loop statement after the while loop in the FIRST code, it will clear the buffer as well. Last, is the '\n' would be read in from the stdin to the buffer ? or to the cArray ?
The loop in the FIRST code block already clears the input buffer as it loops copying all data input by the user to your buffer until there is no more data. Putting readRestOfLine after the loop in this code block will have no effect.

On a side note (but an important one) the FIRST code block is quite poor form as it has the very real risk of enabling a buffer overrun (that is the user enters more data than your buffer, cArray, can hold resulting in the data being written into an unallocated memory location following cArray.
Aug 22 '07 #8
gpraghuram
1,275 Expert 1GB
That is nonsense: you can't flush an input stream. Flushing is something you do
on output streams in case they're buffered. The moment you're attempting to
flush an input stream (if possible), new data may arrive rendering the flushing
useless.

kind regards,

Jos
Thanks for pointing it.
I have used it couple of times in my coding and i havent faced any issues.
This is a new learning for me.

Thanks a lot
Raghuram
Aug 22 '07 #9
primeSo
35
This is because you have called it in the context of the THIRD block, that is a call to getchar() has already been made which has put data into the input buffer.

Let me clarify the operation of getchar() and fgetc(stdin)

When these functions are called first the check the input buffer, if there is data available in the buffer then they return the next character in the buffer and move the buffer pointer(indicating which is the next character to return) on 1 character. If there is no data in the buffer then the request input from the user (on screen cursor flashes). All of the users data up to the next return character is stored in the input buffer, this can be anywhere between 1 (if the just press return) character to lots of characters.

So if you call getchar() or fgetc(stdin) twice in a row then, unless the user just presses return, the program will not request data for the second call as there will already be data available in the input buffer.

The loop in the FIRST code block already clears the input buffer as it loops copying all data input by the user to your buffer until there is no more data. Putting readRestOfLine after the loop in this code block will have no effect.

On a side note (but an important one) the FIRST code block is quite poor form as it has the very real risk of enabling a buffer overrun (that is the user enters more data than your buffer, cArray, can hold resulting in the data being written into an unallocated memory location following cArray.
Oh...I see. Thank you. This has clear my doubt.

May you be well and happy~
prime
Aug 23 '07 #10

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

Similar topics

35
by: Moosebumps | last post by:
Does anyone here find the list comprehension syntax awkward? I like it because it is an expression rather than a series of statements, but it is a little harder to maintain it seems. e.g. you...
4
by: ravinderthakur | last post by:
hi all experts, can anybody explain me the difference between the unsigned char and char in c/c++ langugage. specifically how does this affects the c library fucntion such as strcat,strtok...
28
by: srikanth | last post by:
help me out with the subject
3
by: cinsky | last post by:
Hi, While reading ISO C Standard, I found follow text in 7.19.8.1: size_t fread(void *restrict ptr, size_t SIZE, ...) ... For each object, SIZE calls are made to the fgetc function and the...
18
by: a | last post by:
can someone tell me how to use them thanks
3
by: MargNat | last post by:
Hi, I've wrote a simple c++ program without graphic interface; Now, if I build it with Visual Studio function getchar() works in a way; if I build it with Dev-C++ function getchar() works in...
2
by: david wolf | last post by:
My understanding is that cstdio basically is the same as stdio.h except the functions are in a namspace called std. However when I take a look at the content of the file cstdio, it has the...
26
by: tesh.uk | last post by:
Hi Gurus, I have written the following code with the help of Ivor Horton's Beginning C : // Structures, Arrays of Structures. #include "stdafx.h" #include "stdio.h" #define MY_ARRAY 15
20
by: Senthil-Raja | last post by:
The getchar() function is expected to fetch the next character in the input stream and return it. But, when I wrote a program using this function, it looks like the reading of the input stream...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.