Re: Using fgets() within a function returning an error.
- From: Michael Mair <Michael.Mair@xxxxxxxxxxxxxxx>
- Date: Wed, 27 Jul 2005 23:58:56 +0200
Aomighty wrote:
Hi, I've been creating a simple calculator program that asks whether you want to add, subtract, multiply or divide, asks you for input, and then performs the calculation. Things seem to be going well enough, but I've run into one problem. It seems when I use fgets() or gets() within a function I wrote, it gives me no errors, but when run, doesn't pause for input, but skips past it. I've tried running it inside main() and it runs fine. Compiled using gcc 3.4.3.
Best forget that gets() exists. Note: fgets() is not necessarily the best function for the job, either -- unfortunately, the standard library contains no good function for that job.
Here's the code snippet involved. It's in a header file which is included from main.c. If you run it, I believe that's what will happen.From main, it simply calls add with add().
Please give us a fighting chance: Strip your code down to a minimal example i.e. the minimum program that still exhibits your problem. Throwing us a snippet which may or may not contain the _actual_ error is not helpful. BTW: function definitions are _not_ for header files.
char bigbuff[101];
Unnecessary magic number: #define INPUTSTRLEN 100 char bigbuff[inputlen + 1];
/* The rest of the code.*/
void add(void) {
Note: This interface tells me that the function relies on global data. This is an indicator for not-so-good (vulgo: bad) design.
printf("What numbers do you wish to add?\n");
setupinput();
What does setupinput() do? Can the error be there? Is it possible that you leave some '\n' out there on stdin?
fgets(bigbuff, sizeof(bigbuff), stdin);
sizeof bigbuff is sufficient. You did not check - the return value of fgets() - call ferror() to find out whether there were problems
You may want to check strlen(bigbuff) and maybe fputs(bigbuff, stdout) to start finding the error.
Back to setupinput(): It should contain something along the
lines of
int c;
while ((c = getchar()) != EOF)
if (c == '\n')
break;}
Thanks all.
Cheers Michael -- E-Mail: Mine is an /at/ gmx /dot/ de address. .
- References:
- Using fgets() within a function returning an error.
- From: Aomighty
- Using fgets() within a function returning an error.
- Prev by Date: Re: Should function argument be changed in function body?
- Next by Date: Re: gcc 4 signed vs unsigned char
- Previous by thread: Using fgets() within a function returning an error.
- Next by thread: Question on arrays within a struct and sprintf
- Index(es):