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

another printf question!!

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);

}
>>>>>


Nov 14 '05 #1
12 1782
Remove the spaces from your scanf call:
scanf("%d", &i);

David Barkol
www.neudesic.com

Nov 14 '05 #2
drM
David,
You are a genius!!! But why...I thougth in C spaces did not count?

Nov 14 '05 #3
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.

Nov 14 '05 #4
drM
thank you,

Nov 14 '05 #5
On 2 Feb 2005 14:24:08 -0800, "drM" <md**@comcast.net> wrote:
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),.

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 14 '05 #6
drM
It makes sense now...all part of the learning curve. Thanks for your
input.

Nov 14 '05 #7
drM wrote:
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

Nov 14 '05 #8
On 2 Feb 2005 14:45:11 -0800, in comp.lang.c , "drM" <md**@comcast.net>
wrote:
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;
}

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.ungerhu.com/jxh/clc.welcome.txt>

----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups
----= East and West-Coast Server Farms - Total Privacy via Encryption =----
Nov 14 '05 #9
drM wrote:
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

Nov 14 '05 #10
Mark McIntyre wrote:
On 2 Feb 2005 14:45:11 -0800, in comp.lang.c , "drM" <md**@comcast.net>
wrote:
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.


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
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #11
drM wrote:
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.

--
Email: "jonathan [period] burd [commercial-at] gmail [period] com" sans-WSP

"We must do something. This is something. Therefore, we must do this."
- Keith Thompson
Nov 14 '05 #12
On Wed, 02 Feb 2005 14:30:25 -0800, David Barkol wrote:
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

Nov 14 '05 #13

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

Similar topics

3
by: Murat Tasan | last post by:
so here is another general question about java... why can't you declare an abstract static method. i can envision the case (indeed i have experienced the case) where one would want an...
9
by: Wenjie | last post by:
Hello, Is printf("%d", var); OK for the unsigned long var = SOME_VAR? Or should some other print format be specified? Thanks and best regards, Wenjie
11
by: anonymous | last post by:
Hi CLCers, The program below prints some number and i dont understand why it is behaving like this. I am not supplying the necessary arguments to the printf function and according to my...
11
by: Sensei | last post by:
Hi again! I have ``yet another silly question'', about arrays this time. I've looked through the FAQs in the array & memory sections without finding an answer. I surely didn't look deep enough. ...
1
by: Gunawan | last post by:
Hi All, I have populate data in gridview manually. SqlCommand cmd = new SqlCommand(strSQL, cn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds,...
4
by: Mandragon03 | last post by:
I am looking for a way to take a floating point number and get rid of any extraneous 0's at the end. For instance if I have myFloat = 9999; printf("%f", myFloat); I get 9999.0000. I want to...
11
by: Richard Tobin | last post by:
Please excuse me if this has already been covered. Given char x; is sizeof(x)
3
by: Bint | last post by:
Hi, I have a giant string buffer, and I want to print out small chunks of it at a time. How do I print out, say 20 characters of a string? Is it like this? printf("%20s",mystring); I...
2
by: NickiWood | last post by:
Here we go again... My next assignment is the following: Modify the Payroll Program so that it uses a class to store and retrieve the employee’s name, the hourly rate, and the number of hours...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
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?
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
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
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.