473,396 Members | 1,987 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.

Getc or Getchar is not reading data

HI,
Below is my program. I compiled it through g++. Now strange thing is,
getc is not reading the data instead its printing the previously read
data ! Please some one let me know whats wrong.

#include<stdio.h>
int main()
{

int a;
char c;
scanf("%d",&a);
printf("%d",a);
c = getc(stdin);
printf("%c",c);
}

Thanks In advance.
Subra

Jan 2 '06 #1
19 3693
ma*********@gmail.com said:
HI,
Below is my program. I compiled it through g++. Now strange thing is,
getc is not reading the data instead its printing the previously read
data ! Please some one let me know whats wrong.

#include<stdio.h>
int main()
{

int a;
char c;
scanf("%d",&a);
Read an int's value from the text representation given in stdin. Assuming
nothing goes wrong, that will be read correctly, and the /next/ thing in
the stream - which scanf will take a quick peek at and then quietly stick
back onto the input stream - will be a character that can't be interpreted
as part of the int. For example, it might be a newline character pressed by
the user to indicate that he's finished entering a line of information.
printf("%d",a);
c = getc(stdin);
Ah, let's go and collect that newline character.
printf("%c",c);
And now let's display it.
}

Thanks In advance.


Yes. That's basically the problem here. :-)

By the way, don't forget that main returns an int, so it's best to return an
int from main. In the absence of anything better to return, I suggest 0.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 2 '06 #2
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...

Jan 2 '06 #3
M.B
use one more getchar/getc (to read newline) after reading integer and
before reading the character
or
use scanf to read character also

Thanks
M.B

Jan 2 '06 #4
ma*********@gmail.com a écrit :
Below is my program. I compiled it through g++.
If you are not using a C compiler, all bets are off. Please use gcc or
the like.
Now strange thing is,
getc is not reading the data instead its printing the previously read
data ! Please some one let me know whats wrong.

#include<stdio.h>
int main()
{

int a;
char c;
scanf("%d",&a);
scanf() is a tricky function that you are using badly:

- missing test of the returned value
- missing purge of pending characters.
printf("%d",a);
c = getc(stdin);
Due to the missing purge, getc() reads without waiting. Note that getc()
returns an int and not a char.
printf("%c",c);
}


Better to use fgets() unless you spend a long time to learn how to use
scanf() correctly.

--
A+

Emmanuel Delahaye
Jan 2 '06 #5

<ma*********@gmail.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.com...
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...


scanf(...)

while(getchar() != '\n')
;

c = getchar();
Jan 2 '06 #6
ma*********@gmail.com said:
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...


Yes, it would. Firstly, I forgot to observe last time that you are using
g++, which is a C++ compiler rather than a C compiler. I suggest you use
gcc if you wish to program in C. If you prefer to program in C++, please
ask your C++ questions in comp.lang.c++. Thank you.

Secondly, I would suggest that, to deal with text input of any kind, you
read it as a string with fgets, and then do any necessary conversions of
the data yourself using, for example, strtol or sscanf. Otherwise you'll
just litter your code with getchar calls, at the expense of clarity.

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jan 2 '06 #7

"Richard Heathfield" <in*****@invalid.invalid> wrote in message
news:dp**********@nwrdmz03.dmz.ncs.ea.ibs-infra.bt.com...
ma*********@gmail.com said:
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...


Yes, it would. Firstly, I forgot to observe last time that you are using
g++, which is a C++ compiler rather than a C compiler. I suggest you use
gcc if you wish to program in C. If you prefer to program in C++, please
ask your C++ questions in comp.lang.c++. Thank you.

Secondly, I would suggest that, to deal with text input of any kind, you
read it as a string with fgets, and then do any necessary conversions of
the data yourself using, for example, strtol or sscanf. Otherwise you'll
just litter your code with getchar calls, at the expense of clarity.


Wouldn't something like this work ...

/* could perhaps pass in the buffer size too */
int stdinGet(const char * format, void ** dest)
{
char buffer[100];

if(fgets(buffer, sizeof(buffer), stdin))
{
return sscanf(buffer, format, &(*dest));
}

return 0;
}

int main(void)
{
int n;
char buffer[100];

stdinGet("%d", (void *)&n);

printf("%d\n", n);

stdinGet("%s", (void *)buffer);

printf("%s\n", buffer);

return 0;
}
Jan 2 '06 #8

"pemo" <us***********@gmail.com> wrote in message
news:dp**********@news.ox.ac.uk...

"Richard Heathfield" <in*****@invalid.invalid> wrote in message
news:dp**********@nwrdmz03.dmz.ncs.ea.ibs-infra.bt.com...
ma*********@gmail.com said:
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...


Yes, it would. Firstly, I forgot to observe last time that you are using
g++, which is a C++ compiler rather than a C compiler. I suggest you use
gcc if you wish to program in C. If you prefer to program in C++, please
ask your C++ questions in comp.lang.c++. Thank you.

Secondly, I would suggest that, to deal with text input of any kind, you
read it as a string with fgets, and then do any necessary conversions of
the data yourself using, for example, strtol or sscanf. Otherwise you'll
just litter your code with getchar calls, at the expense of clarity.


Wouldn't something like this work ...

/* could perhaps pass in the buffer size too */
int stdinGet(const char * format, void ** dest)
{
char buffer[100];

if(fgets(buffer, sizeof(buffer), stdin))
{
return sscanf(buffer, format, &(*dest));
}

return 0;
}

int stdinGet(const char * format, void ** dest)
{
char buffer[100];

if(fgets(buffer, sizeof(buffer), stdin))
{
return sscanf(buffer, format, &(*dest));
}

return 0;
}

What's the type of the *dest above?

When used like this ...

int n;

stdinGet("%d", (void *)&n);

The routine's fine, but, if dest's type is changed to void *, gcc complains
about a void * dereference. This seems like a right hack to me - my code
above - but *as ever*, I'm confused: About the type of *dest, why the
compiler doesn't complain about the code 'as is', and why the call to the
routine with 'just' a void * cast isn't complained about - the expression
casts the int * to a void *, yet when this address is passed to stdinGet as
a void **, there's no complaint.

Jan 2 '06 #9
pemo a écrit :
Wouldn't something like this work ...
Hardly... (BTW, <stdio.h> is missing)

123456
123456

æ╣└w◄
/* could perhaps pass in the buffer size too */
int stdinGet(const char * format, void ** dest)
void ** ? Scary !
{
char buffer[100];

if(fgets(buffer, sizeof(buffer), stdin))
{
return sscanf(buffer, format, &(*dest));
This '&(*' thingy sounds weird...
}

return 0;
}

int main(void)
{
int n;
char buffer[100];

stdinGet("%d", (void *)&n);
Don't use cast to hide bad pratices... It's evil and will bite you some
day...
printf("%d\n", n);
stdinGet("%s", (void *)buffer);
Are you a member of the random programming cult ?
printf("%s\n", buffer);
return 0;
}


Devillish... Far enough to burn in Hell...

Why do you return the value of sscanf() if you never test it ?

--
A+

Emmanuel Delahaye
Jan 2 '06 #10
pemo a écrit :
Wouldn't something like this work ...
Hardly... (BTW, <stdio.h> is missing)

123456
123456

æ╣└w◄
/* could perhaps pass in the buffer size too */
int stdinGet(const char * format, void ** dest)
void ** ? Scary !
{
char buffer[100];

if(fgets(buffer, sizeof(buffer), stdin))
{
return sscanf(buffer, format, &(*dest));
This '&(*' thingy sounds weird...
}

return 0;
}

int main(void)
{
int n;
char buffer[100];

stdinGet("%d", (void *)&n);
Don't use cast to hide bad pratices... It's evil and will bite you some
day...
printf("%d\n", n);
stdinGet("%s", (void *)buffer);
Are you a member of the random programming cult ?
printf("%s\n", buffer);
return 0;
}


Devillish... Far enough to burn in Hell...

Why do you return the value of sscanf() if you never test it ?

Try this

#include <stdio.h>

int stdinGet (int* p_dest)
{
int ret = 0;

if (p_dest != NULL)
{
char buffer[32];

if (fgets(buffer, sizeof buffer, stdin) != NULL)
{
ret = sscanf (buffer, "%d", p_dest);
}
}
return ret;
}

int main(void)
{
int n;

int ret = stdinGet(&n);

if (ret == 1)
{
printf("%d\n", n);
}

return 0;
}
--
A+

Emmanuel Delahaye
Jan 2 '06 #11

"Emmanuel Delahaye" <em***@YOURBRAnoos.fr> wrote in message
news:43***********************@nan-newsreader-07.noos.net...
pemo a écrit :
Wouldn't something like this work ...
Hardly... (BTW, <stdio.h> is missing)

123456
123456

æ??w?


What's the test data entered?
/* could perhaps pass in the buffer size too */
int stdinGet(const char * format, void ** dest)


void ** ? Scary !


See my other post on this.
{
char buffer[100];

if(fgets(buffer, sizeof(buffer), stdin))
{
return sscanf(buffer, format, &(*dest));


This '&(*' thingy sounds weird...
}

return 0;
}

int main(void)
{
int n;
char buffer[100];

stdinGet("%d", (void *)&n);


Don't use cast to hide bad pratices... It's evil and will bite you some
day...
printf("%d\n", n);
stdinGet("%s", (void *)buffer);


Are you a member of the random programming cult ?


??
printf("%s\n", buffer);
return 0;
}


Devillish... Far enough to burn in Hell...


Why do you return the value of sscanf() if you never test it ?


Do you test printf's return value?
Jan 2 '06 #12
"pemo" <us***********@gmail.com> writes:
<ma*********@gmail.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.com...
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...


scanf(...)

while(getchar() != '\n')
;

c = getchar();


If getchar() returns EOF before returning '\n', this is an infinite loop.

What is the purpose of that last line? It reads the first character
on the line following the one your just read; was that what you
intended?

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Jan 2 '06 #13

--
Pradyut
http://pradyut.tk
http://groups.yahoo.com/group/d_dom/
http://groups-beta.google.com/group/oop_programming
India
<ma*********@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
HI,
Below is my program. I compiled it through g++. Now strange thing is,
getc is not reading the data instead its printing the previously read
data ! Please some one let me know whats wrong.

This is not a good solution but a works well

#include<stdio.h>
int main()
{

int a;
char c;
scanf("%d",&a);
printf("%d",a);
fflush(stdin);
c = getc(stdin);
printf("\nThis is the charachter %c",c);
return 0;
}

Although it's a very typical solution to such problems
#include<stdio.h>
int main()
{

int a;
char c;
scanf("%d",&a);
printf("%d",a);
c = getc(stdin);
printf("%c",c);
}

Thanks In advance.
Subra

Jan 2 '06 #14
Pradyut a écrit :

<nothing>

Because you have ansewerd after the signature separator, none of your
prose has been quoted (Thunderbird). Please don't do that.

--
A+

Emmanuel Delahaye
Jan 2 '06 #15
Pradyut a écrit :
This is not a good solution but a works well
No, it doesn't work at all.
fflush(stdin);


This statement invokes an undefined behaviour. It has been explained
before in the thread that you should have read before posting...

--
A+

Emmanuel Delahaye
Jan 2 '06 #16
Pradyut a écrit :

<nothing>

Because you have answered after the signature separator, none of your
prose has been quoted (Thunderbird). Please don't do that.

--
A+

Emmanuel Delahaye
Jan 2 '06 #17
Pradyut wrote:
--
Pradyut http://pradyut.tk
<snip>

Your signature (i.e. the bit I've quoted part of above) belongs *below*
the post, not above it. A number of news readers automatically remove
signatures when replying (or even when displaying) so putting the
signature above is a real pain for some people. Search for quotefix if
you want to get OE to behave a bit better.
> HI,
> Below is my program. I compiled it through g++. Now strange thing is,
> getc is not reading the data instead its printing the previously read
> data ! Please some one let me know whats wrong.
>


This is not a good solution but a works well

#include<stdio.h>
int main()
{

int a;
char c;
scanf("%d",&a);
printf("%d",a);
fflush(stdin);


No, no, a thousand times no. We've just had a few posts saying the
fflush is defined for output streams only, so *why* are you suggesting
using it on an input stream?
c = getc(stdin);
printf("\nThis is the charachter %c",c);
return 0;
}

Although it's a very typical solution to such problems


<snip>

It may be typical amongst those who have learnt from bad books, but it
is not typical amongst those who have a good understanding of C.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Jan 3 '06 #18
M.B
this dosent work
you cannot do fflush on input buffers
see "man fflush" first

Jan 3 '06 #19

"Keith Thompson" <ks***@mib.org> wrote in message
news:ln************@nuthaus.mib.org...
"pemo" <us***********@gmail.com> writes:
<ma*********@gmail.com> wrote in message
news:11*********************@g49g2000cwa.googlegro ups.com...
Then how can I read the Integer and the Character ?? Any solution ???
Its happening consistantly on windows as well as on Linux...


scanf(...)

while(getchar() != '\n')
;

c = getchar();


If getchar() returns EOF before returning '\n', this is an infinite loop.

What is the purpose of that last line? It reads the first character
on the line following the one your just read; was that what you
intended?


Oops - yes, it was intended, but it shouldn't have been copied into my post.
Jan 3 '06 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
by: William L. Bahn | last post by:
I'm sure this has been asked before, and I have looked in the FAQ, but I'm looking for an explanation for the following: The functions pairs: gets()/fgets() puts()/fputs() printf()/fprintf()...
3
by: Vinicius | last post by:
Hello, the following code does not work: " .... void main(void) { char option; printf("Choose an option: ");
8
by: Bill Cunningham | last post by:
Would getc and ungetc be the best and most simple what to parse expressions for a parser? Bill
11
by: Mars | last post by:
char c; int i; scanf("%d",&i); c=getchar(); I want to read a integer and a character in 2 lines. Why the getchar always get the \n character from the last line????? (Sorry for my newbie...
11
by: TTroy | last post by:
Hello C programmers, Can someone tell me why ungetc can't sent back EOF, but it's sister function getc has no trouble sending it to us? For a file, this might not make a difference, but for an...
9
by: JuanK | last post by:
hello, i'm trying to read a character from console just like getc function in c languaje i'm trying with WINAPI but dont works at this time.. other methods like clear screen works OK with the...
1
by: White Spirit | last post by:
I'm trying to use getchar() to read alphanumeric data as follows:- char input; /* Take a string of input and remove all spaces therein */ int j = 0; while ((input = getchar()) != '\n') { if...
7
by: hzmonte | last post by:
My C program has the following: static int skip_space(FILE *fp, int *line, int c) { int i = 0; if(feof(fp)) { printf("in skip feof ...\n"); } printf("in skip start fp=%p line=%d c=%d\n", fp,...
5
by: Richard Weeks | last post by:
Below is a fragment from a program that calculates statistics on x,y data. I want the user to be able to predict one or more predicted values of y from x, given the line of best fit. I have a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
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,...

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.