another printf question!!

D

drM

I have looked at the faq and queried the archives, but cannot seem to
be able to get this to work. It's the usual factorial recursive
function, but that is not the problem. It hangs after the user enters a
number. However, as I indicate, if one adds something else after the
number, the function proceeds and finishes successfully.

I would appreciate some helpful hints.
thanks in advance.

#include <stdio.h>
#include <math.h>

int factorial( int);
main() {

int i, k;

printf ( "Please enter a number "); // <<<<< seems to hang here if
user enters number only, but
// works if user enters number eg 8 plus something else eg the letter
"m".
scanf (" %d ", &i);

k = factorial (i);
printf ( " the factorial of %d is %d\n ", i, k);

return (0);

}


int factorial ( int j){
if (j == 1)

return 1;

return j * factorial(j-1);

}
 
D

David Barkol

scanf reads formatted data from the standard input stream. This means
that if you have a format like: "%d %d" then scanf will not return
until you enter in two numbers seperated by a space. For example: 24
14. When dealing with formatting, spaces always count.
 
A

Alan Balmer

David,
You are a genius!!! But why...I thougth in C spaces did not count?

Spaces in quotations are significant. In your scanf call, you could
write
scanf ( "%d " , &i );

without making a difference (except to the unfortunate person reading
it),.
 
D

Default User

drM said:
thank you,

Please learn to use the correct reply method when using the Google
interface. Click "show options" to expand the header of the message you
are replying to, then the Reply shown there. Don't use the one at the
bottom of the message. You'll then have proper attributions and quotes,
so people can understand what you are refering to.




Brian
 
M

Mark McIntyre

It makes sense now...all part of the learning curve. Thanks for your
input.

You may also want to consider not using scanf for user input - its not very
robust or secure. Its often better to use fgets and sscanf. As you've
found scanf can't handle unexpected input very well.

What does this programme do, if the user types in "one" as the response?

#include <stdio.h>

int main(void)
{
int x=1;

printf("think of a number\n");
while(x > 0)
scanf("%d", &x);

return 0;
}
 
T

Taran

drM said:
I have looked at the faq and queried the archives, but cannot seem to
be able to get this to work. It's the usual factorial recursive
function, but that is not the problem. It hangs after the user enters a
number. However, as I indicate, if one adds something else after the
number, the function proceeds and finishes successfully.

I would appreciate some helpful hints.
thanks in advance.


#include <stdio.h>
#include <math.h>

int factorial( int);
main() {

int i, k;

printf ( "Please enter a number "); // <<<<< seems to hang here if
user enters number only, but
// works if user enters number eg 8 plus something else eg the letter
"m".
scanf (" %d ", &i);

k = factorial (i);
printf ( " the factorial of %d is %d\n ", i, k);

return (0);

}


int factorial ( int j){
if (j == 1)

return 1;

return j * factorial(j-1);

}

I faced the same problems when I was new to C. Learned the hard way
though. Have been paranoid about scanf ever since. :)
A book on C by Schaum's Series was helpful regarding the nuances on
scanf. Sorry don't excatly remember the name. I rather you go thru it
once.

HTH

Regards,
Taran
 
M

Michael Mair

Mark said:
You may also want to consider not using scanf for user input - its not very
robust or secure. Its often better to use fgets and sscanf. As you've
found scanf can't handle unexpected input very well.

An addendum (without wanting to break up old trenches):
scanf() can be used in a moderately safe way (others argue in the
only safe way compared to fgets()+sscanf) if used correctly.
If you want to use scanf(), at least check the return value.
scanf() (and also all other *scanf() functions) returns the number
of input items successfully read.

Examples:

if(scanf("%d",&num)!=1) {
/* error: we did not get our number */
}

if( (ret=scanf("%20s is the number %d",name,&num)) != 2 ) {
/* error: ret 1 .. Name was read correctly
** 0 .. No input item read
** <0 .. encoding or other bad error */
}

See also the FAQ 12.17 ('\n' and ' ' are equivalent for our
purposes) to 12.20; if you follow the fgets() advice maybe also
12.23.
You can start from here:
http://www.eskimo.com/~scs/C-faq/top.html

BTW: Read the _complete_ list of _questions_, better of course
the whole FAQ. No kidding.

What does this programme do, if the user types in "one" as the response?

#include <stdio.h>

int main(void)
{
int x=1; char buffer[80];

printf("think of a number\n");
while(x > 0)
scanf("%d", &x);
{
fgets(buffer, 80, stdin);
sscanf(buffer, "%d", &x);
}
admittedly probably puts less load on your box and
you have not the trouble of having to discard faulty input;
but if you scan with Pop's Device anyway, you will have the
same effect -- without having to ask yourself whether you
left crap from the last input line out there effectively
leading to a different input (compared to what you may have
intended).
Apart from that, scanf() can handle an input "1\n2\n" just
like "1 2\n", which may come in handy.
return 0;
}

Cheers
Michael
 
J

Jonathan Burd

drM said:
I have looked at the faq and queried the archives, but cannot seem to
be able to get this to work. It's the usual factorial recursive
function, but that is not the problem. It hangs after the user enters a
number. However, as I indicate, if one adds something else after the
number, the function proceeds and finishes successfully.

I would appreciate some helpful hints.
thanks in advance.



#include <stdio.h>
#include <math.h>

Don't need math.h.
int factorial( int);
main() {

``implicit int"? Please make the return type explicit.
Choose one of these formats for your main function definition:

int main (void) ...
or
int main (int argc, char *argv[]) ...
or
any format type-compatible with the above.
int i, k;

printf ( "Please enter a number "); // <<<<< seems to hang here if

It's best to use fflush(stdout) after a printf call, the format string
of which does not end with a '\n'. This way you can be sure that
your prompt will definitely be displayed.
user enters number only, but
// works if user enters number eg 8 plus something else eg the letter
"m".
scanf (" %d ", &i);

Here's the problem. This should be scanf("%d", &i);
Whitespace characters inside strings *do* count.
A _better_ approach is to read input from stdin into a string buffer
using fgets(), and then use sscanf() to read the integer from
the string buffer into your variable, although you can use scanf
if you know how to use it properly.

[Note: Remember that fgets() will also include an
additional '\n' just before the EOS (end of the string == '\0').]
k = factorial (i);
printf ( " the factorial of %d is %d\n ", i, k);

return (0);

Although, it is not incorrect, do not do this because return is not a
function.
}


int factorial ( int j){
if (j == 1)

return 1;

return j * factorial(j-1);

}

Including a whitespace character at the end of a scanf()
format string is a common mistake. For example, see what this does:

/* err_scanf_space_end.c */
#include <stdio.h>

int
main (void)
{
int foo;
int ret;

printf ("Enter an integer: ");
fflush (stdout);
if ((ret = scanf ("%d ", &foo)) == 1)
printf ("foo: %d\n", foo);

/* ... */

return 0;
}

Output:
=======
enter an integer: 123


4
foo: 123
=======

Don't include whitespace characters at the end of a scanf format string.
Whitespace characters inside strings *do* count.

[Please don't use Google to post. It is buggy and reading
improperly formatted code hurts the eyes. Many people will
simply ignore posts with improperly formatted code. I suggest you
get a decent NG client and subscribe to a NG server.]

Regards,
Jonathan.
 
L

Lawrence Kirby

scanf reads formatted data from the standard input stream. This means
that if you have a format like: "%d %d" then scanf will not return
until you enter in two numbers seperated by a space. For example: 24
14. When dealing with formatting, spaces always count.

It will also return if you enter input it can't match. So if you enter X
scanf() will return but won't have converted any numbers. You can test for
this in scanf()'s return value, it returns the number of arguments
assigned to i.e. 2 for correct input in this case.

Lawrence
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,159
Messages
2,570,879
Members
47,414
Latest member
GayleWedel

Latest Threads

Top