473,834 Members | 1,363 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comprehension problem between getchar() and fgetc().

35 New Member
// 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 5153
primeSo
35 New Member
: ( , no one reply me , i need clarification badly on this issue.
Aug 22 '07 #2
gpraghuram
1,275 Recognized Expert Top Contributor
: ( , 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 Recognized Expert MVP
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 Recognized Expert Moderator Expert
Actually
Expand|Select|Wrap|Line Numbers
  1. fflush(stdin);
  2.  
invokes undefined behaviour, read this
Aug 22 '07 #5
Banfa
9,065 Recognized Expert Moderator Expert
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 New Member
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 Recognized Expert Moderator Expert
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(indicat ing 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 Recognized Expert Top Contributor
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 New Member
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(indicat ing 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
3004
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 could do: result = for element in list: if element == 'blah':
4
1042
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 etc and their implementation.the way compiler treats them and the scenarios where one
28
9894
by: srikanth | last post by:
help me out with the subject
3
3357
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 results stored, in the order read, in an array of unsigned char exactly overlaying the object.
18
460
by: a | last post by:
can someone tell me how to use them thanks
3
5676
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 another way. Why? Then, another question: Is there a specific function to exit program pressing any button?
2
14592
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 following lines inside only: -------content of cstdio on red hat linux enterprise 3---- #ifndef __CSTDIO__ #define __CSTDIO__ #include <stdio.h> #endif
26
4546
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
636
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 happens only after I press the ENTER key. Please someone explain why this is happening. Regards, Senthil-Raja.
0
9796
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10790
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10505
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10214
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9329
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7755
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6952
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5790
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4425
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.