473,322 Members | 1,755 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,322 software developers and data experts.

Help with scanf

I'm writing a program for that takes dates as input using scanf. I
want to verify that the user is inputting a full 4 digits for the
year. How do I do this? I know that the return value on printf is the
number of printed characters; so if I could somehow get my year
variable to store the leading zeros, I could just run a check:

int dummy = 0;

dummy = printf("%d", year);

if (dummy != 4)
{
...do something...
}
Nov 14 '05 #1
20 2857
On 31 Mar 2004 19:54:06 -0800, ma****@tamu.edu (Sivarn) wrote:
I'm writing a program for that takes dates as input using scanf. I
want to verify that the user is inputting a full 4 digits for the
year. How do I do this? I know that the return value on printf is the
number of printed characters; so if I could somehow get my year
variable to store the leading zeros, I could just run a check:

int dummy = 0;

dummy = printf("%d", year);

if (dummy != 4)
{
...do something...
}


Wait a minute...you started by asking about scanf, and you say you want to
verify the input? Then I'm sure you'd rather not have to print the value
just in order to be able to validate the user input, right?

You certainly don't have to. Let's go ahead and use scanf, because that's
how you say you're doing it (but scanf is essentially useless if you need
serious validation of input. More on that later...):

int count;
int year;
count = scanf("%d", &year);

Note that you must provide the & on year, since scanf has to know /where/
to put the value. count tells you how many "items" were scanned; it could
be 0 if the user didn't type a number. So let's test that:

if (count != 1)
{
printf("Bad input. You lose.\n");
exit(1);
}

(Of course you might choose to do something other than exit here.)

So, how to test for 4 digits? Well, the easiest way I can think of is to
just test for a valid (or invalid) range:

if (year < 1900 || year > 2030) /* or whatever */
{
printf("Bad year. You're outa here.\n");
exit (1);
}

If you /really/ want "any 4 digit number", just test that it is between
1000 and 9999.

So that takes care of that. Now we can improve the input. sscanf is a royal
pain to work with, because if the user just keeps pressing enter, it'll
merrily echo blank lines till doomsday (it ignores leading whitespace,
including newlines). And if the user presses, say, a letter when scanf is
looking for a number, that letter persists on the input stream the /next/
time you try to read a number, further wreaking havoc.

Better to force a single line of input, and then process it. I like to use
fgets to read a line into a buffer, and then sscanf to do the conversion.
sscanf is a lot like scanf, but it reads input from a string buffer instead
of from the standard input. Putting all of that together with some
re-prompting logic, here's a program for you:

#include <stdio.h>

int main()
{
int year;
char buffer[100];

while (1)
{
printf("Please enter a year: ");
fgets(buffer, 100, stdin);
if (sscanf(buffer, "%d", &year) != 1)
printf("that wasn't a number! Try again....\n");
else if (year < 1900 || year > 2030)
printf("Bad year! Must be between 1900 and 2030."
" Try again...\n");
else
break;
}

printf("Success! your year is %d\n", year);

return 0;
}

That is something you can now expand to support as much processing on that
line of input as you please, without running into a slew of problems you'd
get from using just scanf.

Good luck,
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #2
On Thu, 01 Apr 2004 04:39:57 GMT, Leor Zolman <le**@bdsoft.com> wrote:
So that takes care of that. Now we can improve the input. sscanf is a royal
pain to work with


That should have read: /scanf/ is a royal pain...oops.
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #3
"Leor Zolman" <le**@bdsoft.com> wrote:
if (count != 1)
{
printf("Bad input. You lose.\n");
exit(1);
}
1 is not a portable exit code (termination status); it might have unexpected
effects. If you want to indicate failure, do so explicitly with the macro
EXIT_FAILURE. The only portable exit codes are 0, EXIT_SUCCESS and
EXIT_FAILURE. The value of EXIT_SUCCESS may or may not be zero, but has the
same effect.
exit(EXIT_FAILURE);
EXIT_FAILURE is defined in <stdlib.h> which you should already have included
for the exit function itself. It might expand to 1 or to any other value
other than zero.

Also, please don't post tabs to newsgroups. Indenting should be done with
spaces.

[...]
#include <stdio.h>

int main()
{
int year;
char buffer[100];

while (1)
{
printf("Please enter a year: ");
Here you need to flush the stdout buffer to ensure that the prompt is
displayed to the screen before you wait for user input.
fflush(stdout);
fgets(buffer, 100, stdin);
I'd avoid magic numbers and check for success/failure
if(fgets(buffer, sizeof buffer, stdin) == NULL)
{
printf("There was a problem reading your input.\n");
exit(EXIT_FAILURE);
}

At this point if the user has entered a number outside the range of int, the
behaviour of sscanf will be undefined. This is a good point to validate the
input before continuing.
if(strlen(buffer) != 5 || strspn(buffer, "0123456789\n") != 5)
{
printf("That wasn't a four digit number! Try again...\n");
}
else
if (sscanf(buffer, "%d", &year) != 1)
printf("that wasn't a number! Try again....\n");
else if (year < 1900 || year > 2030)
printf("Bad year! Must be between 1900 and 2030."
" Try again...\n");
else
break;
}

printf("Success! your year is %d\n", year);

return 0;
}


--
Simon.
Nov 14 '05 #4
"Simon Biber" <ne**@ralminNOSPAM.cc> wrote:
"Leor Zolman" <le**@bdsoft.com> wrote:
#include <stdio.h>
I forgot to add that my changes to the code below require
#include <stdlib.h> /* for exit and EXIT_FAILURE */
#include <string.h> /* for strlen and strspn */
int main()
{
int year;
char buffer[100];

while (1)
{
printf("Please enter a year: ");
Here you need to flush the stdout buffer to ensure that the prompt is
displayed to the screen before you wait for user input.
fflush(stdout);
fgets(buffer, 100, stdin);


I'd avoid magic numbers and check for success/failure
if(fgets(buffer, sizeof buffer, stdin) == NULL)
{
printf("There was a problem reading your input.\n");
exit(EXIT_FAILURE);
}

At this point if the user has entered a number outside the range of int,

the behaviour of sscanf will be undefined. This is a good point to validate the input before continuing.
if(strlen(buffer) != 5 || strspn(buffer, "0123456789\n") != 5)
{
printf("That wasn't a four digit number! Try again...\n");
}
else
if (sscanf(buffer, "%d", &year) != 1)
printf("that wasn't a number! Try again....\n");
else if (year < 1900 || year > 2030)
printf("Bad year! Must be between 1900 and 2030."
" Try again...\n");
else
break;
}

printf("Success! your year is %d\n", year);

return 0;
}


--
Simon.
Nov 14 '05 #5

On Thu, 1 Apr 2004, Leor Zolman wrote:

On 31 Mar 2004 19:54:06 -0800, ma****@tamu.edu (Sivarn) wrote:
I'm writing a program for that takes dates as input using scanf. I
want to verify that the user is inputting a full 4 digits for the
year. How do I do this?
Let's go ahead and use scanf, because that's how you say you're
doing it (but scanf is essentially useless if you need
serious validation of input. More on that later...):
Now, just a minute there! I'll grant you that scanf is less than
completely useful for *complex* validation, but *serious* validation
can indeed be performed, if you're willing to put up with the syntax.
I like scanf. :-)

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void)
{
char buffer[5] = {0};
char *bp;
int k;
int year;

puts("Enter a 4-digit year now.");
if (1 != scanf(" %4[0123456789]", buffer)) {
puts("No digits entered!");
}
else {
year = strtol(buffer, &bp, 10);
if (bp != buffer+4) {
puts("Fewer than 4 digits entered!");
}
else {
printf("You entered the (valid) year %d.\n", year);
}
}

k = getchar();
if (!isspace(k)) {
puts("You left some input at the end of your line.");
}
ungetc(k, stdin);

return 0;
}

So, how to test for 4 digits? Well, the easiest way I can think of is to
just test for a valid (or invalid) range:

if (year < 1900 || year > 2030) /* or whatever */
Presumably the OP's problem was that he wanted *four digits of input*,
not merely a number in the range 1000-9999; i.e., counting leading
zeroes.
So that takes care of that. Now we can improve the input. sscanf is a royal
pain to work with, because if the user just keeps pressing enter, it'll
merrily echo blank lines till doomsday (it ignores leading whitespace,
including newlines). And if the user presses, say, a letter when scanf is
looking for a number, that letter persists on the input stream the /next/
time you try to read a number, further wreaking havoc.
OTOH, sometimes that's a nice behavior, not least because it's easy
to predict its behavior. As opposed to...
Better to force a single line of input, and then process it.


....fgets, which reads either up to the first newline, *or* until its
buffer runs out, whichever comes first. :) Not that it's impossible
to do good stuff with fgets; it's not. But scanf's behavior isn't
entirely illogical, either.

HTH,
-Arthur

Nov 14 '05 #6
On Thu, 01 Apr 2004 05:29:51 GMT, "Simon Biber" <ne**@ralminNOSPAM.cc>
wrote:
"Leor Zolman" <le**@bdsoft.com> wrote:
if (count != 1)
{
printf("Bad input. You lose.\n");
exit(1);
}
1 is not a portable exit code (termination status); it might have unexpected
effects. If you want to indicate failure, do so explicitly with the macro
EXIT_FAILURE. The only portable exit codes are 0, EXIT_SUCCESS and
EXIT_FAILURE. The value of EXIT_SUCCESS may or may not be zero, but has the
same effect.
exit(EXIT_FAILURE);
EXIT_FAILURE is defined in <stdlib.h> which you should already have included
for the exit function itself. It might expand to 1 or to any other value
other than zero.


Sorry, old habits die hard ;-)

Also, please don't post tabs to newsgroups. Indenting should be done with
spaces.
Arghh. I forgot this time; but generally I've been pretty good. In fact,
I'd just come up with an Epsilon macro that with one keystroke a)
untabifies my edit buffer, b) copies it into the clipboard, and c)
re-tabifies. Now I just have to remember to /use/ it.

[...]
#include <stdio.h>

int main()
{
int year;
char buffer[100];

while (1)
{
printf("Please enter a year: ");
Here you need to flush the stdout buffer to ensure that the prompt is
displayed to the screen before you wait for user input.
fflush(stdout);


Is that actually required for stdout if you then pause to read from stdin?
Where'd I get the impression there was some sort of special case for
that...
fgets(buffer, 100, stdin);


I'd avoid magic numbers and check for success/failure
if(fgets(buffer, sizeof buffer, stdin) == NULL)
{
printf("There was a problem reading your input.\n");
exit(EXIT_FAILURE);
}

At this point if the user has entered a number outside the range of int, the
behaviour of sscanf will be undefined. This is a good point to validate the
input before continuing.
if(strlen(buffer) != 5 || strspn(buffer, "0123456789\n") != 5)
{
printf("That wasn't a four digit number! Try again...\n");
}
else
if (sscanf(buffer, "%d", &year) != 1)
printf("that wasn't a number! Try again....\n");
else if (year < 1900 || year > 2030)
printf("Bad year! Must be between 1900 and 2030."
" Try again...\n");
else
break;
}

printf("Success! your year is %d\n", year);

return 0;
}


Thanks!
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #7
On Thu, 1 Apr 2004 02:54:31 -0500 (EST), "Arthur J. O'Dwyer"
<aj*@nospam.andrew.cmu.edu> wrote:

On Thu, 1 Apr 2004, Leor Zolman wrote:

On 31 Mar 2004 19:54:06 -0800, ma****@tamu.edu (Sivarn) wrote:
>I'm writing a program for that takes dates as input using scanf. I
>want to verify that the user is inputting a full 4 digits for the
>year. How do I do this?
Let's go ahead and use scanf, because that's how you say you're
doing it (but scanf is essentially useless if you need
serious validation of input. More on that later...):


Now, just a minute there! I'll grant you that scanf is less than
completely useful for *complex* validation, but *serious* validation
can indeed be performed, if you're willing to put up with the syntax.
I like scanf. :-)


I think the way it ignores leading newlines alone is enough to justify
dispensing with it for interactive use. Do you really want to have to
include text such as "If you press Enter first and nothing happens, don't
keep wailing on the Enter key! Try something /else/!" as part of your
prompt?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(void)
{
char buffer[5] = {0};
char *bp;
int k;
int year;

puts("Enter a 4-digit year now.");
if (1 != scanf(" %4[0123456789]", buffer)) {
puts("No digits entered!");
}
else {
year = strtol(buffer, &bp, 10);
if (bp != buffer+4) {
puts("Fewer than 4 digits entered!");
}
else {
printf("You entered the (valid) year %d.\n", year);
}
}

k = getchar();
if (!isspace(k)) {
puts("You left some input at the end of your line.");
}
ungetc(k, stdin);

return 0;
}

So, how to test for 4 digits? Well, the easiest way I can think of is to
just test for a valid (or invalid) range:

if (year < 1900 || year > 2030) /* or whatever */
Presumably the OP's problem was that he wanted *four digits of input*,
not merely a number in the range 1000-9999; i.e., counting leading
zeroes.


I'm not sure that's what he really wanted; It looks like he only wanted the
leading zeros as part of his printf-related validation scheme for the
input. I don't know, but the fact he's putting the year into an int pretty
much excludes his possible use for those leading zeros...
So that takes care of that. Now we can improve the input. sscanf is a royal
pain to work with, because if the user just keeps pressing enter, it'll
merrily echo blank lines till doomsday (it ignores leading whitespace,
including newlines). And if the user presses, say, a letter when scanf is
looking for a number, that letter persists on the input stream the /next/
time you try to read a number, further wreaking havoc.
OTOH, sometimes that's a nice behavior, not least because it's easy
to predict its behavior. As opposed to...
Better to force a single line of input, and then process it.


...fgets, which reads either up to the first newline, *or* until its
buffer runs out, whichever comes first. :) Not that it's impossible
to do good stuff with fgets; it's not. But scanf's behavior isn't
entirely illogical, either.


A sane user interface has always been /much/ easier to get working for me
using fgets/sscanf, but of course YMMV.

HTH,
-Arthur


I expected to get some critique of this from folks, and wasn't
disappointed. I still don't quite have all the "modern C" idioms down
(EXIT_FAILURE seems to come real hard, perhaps because I just balk at
having to type it out...), but I'm slowly getting there ;-)
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #8
Hello

If you want some string to be has leading zero's

use
printf("%04d",1); => "0001"
printf("%04d",10001); => "10001"
printf("%04.4d",10001); => "1000"
printf("%4d",1); => " 1"
for a complete set of pssiblelities look in a good C manual.

Greetings

ma****@tamu.edu (Sivarn) wrote in message news:<be**************************@posting.google. com>...
I'm writing a program for that takes dates as input using scanf. I
want to verify that the user is inputting a full 4 digits for the
year. How do I do this? I know that the return value on printf is the
number of printed characters; so if I could somehow get my year
variable to store the leading zeros, I could just run a check:

int dummy = 0;

dummy = printf("%d", year);

if (dummy != 4)
{
...do something...
}

Nov 14 '05 #9
"Leor Zolman" <le**@bdsoft.com> wrote:
"Simon Biber" <ne**@ralminNOSPAM.cc> wrote:
"Leor Zolman" <le**@bdsoft.com> wrote:
printf("Please enter a year: ");


Here you need to flush the stdout buffer to ensure that the
prompt is displayed to the screen before you wait for user
input.
fflush(stdout);


Is that actually required for stdout if you then pause to read
from stdin? Where'd I get the impression there was some sort
of special case for that...


Although many systems do implement a special case that they flush stdout's
buffer when you read from stdin, it is still required on some systems so
it's a good idea to include the fflush(stdout) when writing portable code.

--
Simon.
Nov 14 '05 #10
On Thu, 01 Apr 2004 13:45:02 GMT, "Simon Biber" <ne**@ralminNOSPAM.cc>
wrote:
"Leor Zolman" <le**@bdsoft.com> wrote:
"Simon Biber" <ne**@ralminNOSPAM.cc> wrote:
>"Leor Zolman" <le**@bdsoft.com> wrote:
> > printf("Please enter a year: ");
>
> Here you need to flush the stdout buffer to ensure that the
> prompt is displayed to the screen before you wait for user
> input.
> fflush(stdout);


Is that actually required for stdout if you then pause to read
from stdin? Where'd I get the impression there was some sort
of special case for that...


Although many systems do implement a special case that they flush stdout's
buffer when you read from stdin, it is still required on some systems so
it's a good idea to include the fflush(stdout) when writing portable code.


Well, then, that's the last straw. I've been driven to actually create a
checklist, because there's no /way/ I'm going to remember to flush my
stdout before reading stdin unless I have that written down somehwere
(grumble...) ;-)
-leor
--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #11
In <be**************************@posting.google.com > ma****@tamu.edu (Sivarn) writes:
I'm writing a program for that takes dates as input using scanf. I
want to verify that the user is inputting a full 4 digits for the
year. How do I do this?


Try engaging your brain. What is the smallest 4-digit number? 1000.
What is the largest 4-digit number? 9999. So, the test for 4-digit
numbers (with no preceding zeros) becomes:

if (year >= 1000 && year <= 9999) /* good input */ ;
else /* bad input */ ;

Now, if your number is supposed to be a year, you may want to restrict
the valid input range even further, using exactly the same technique.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #12
"Leor Zolman" <le**@bdsoft.com> wrote in message
news:56********************************@4ax.com...
printf("Please enter a year: ");
Here you need to flush the stdout buffer to ensure that the prompt is
displayed to the screen before you wait for user input.
fflush(stdout);


Is that actually required for stdout if you then pause to read from stdin?


Yes, if you want to guarantee the output appears before
the input request.
Where'd I get the impression there was some sort of special case for
that...


Probably from C++, where cin/cout are 'tied', causing
the output to appear first automatically.

-Mike
Nov 14 '05 #13

"Leor Zolman" <le**@bdsoft.com> wrote in message
news:1s********************************@4ax.com...
On Thu, 01 Apr 2004 13:45:02 GMT, "Simon Biber" <ne**@ralminNOSPAM.cc>
wrote:
"Leor Zolman" <le**@bdsoft.com> wrote:
"Simon Biber" <ne**@ralminNOSPAM.cc> wrote:
>"Leor Zolman" <le**@bdsoft.com> wrote:
> > printf("Please enter a year: ");
>
> Here you need to flush the stdout buffer to ensure that the
> prompt is displayed to the screen before you wait for user
> input.
> fflush(stdout);

Is that actually required for stdout if you then pause to read
from stdin? Where'd I get the impression there was some sort
of special case for that...
Although many systems do implement a special case that they flush stdout'sbuffer when you read from stdin, it is still required on some systems so
it's a good idea to include the fflush(stdout) when writing portable

code.
Well, then, that's the last straw. I've been driven to actually create a
checklist, because there's no /way/ I'm going to remember to flush my
stdout before reading stdin unless I have that written down somehwere
(grumble...) ;-)


Or you see your program behave 'wrongly', i.e. it waits
for input before a 'prompt' appears (I've actually had this
happen to me on some older DOS platforms -- my lesson
was a 'real-world' one, so it stuck. :-)).

-Mike
Nov 14 '05 #14
Simon Biber wrote:
"Leor Zolman" <le**@bdsoft.com> wrote:
"Simon Biber" <ne**@ralminNOSPAM.cc> wrote:
>"Leor Zolman" <le**@bdsoft.com> wrote:
> > printf("Please enter a year: ");
>
> Here you need to flush the stdout buffer to ensure that the
> prompt is displayed to the screen before you wait for user
> input.
> fflush(stdout);


Is that actually required for stdout if you then pause to read
from stdin? Where'd I get the impression there was some sort
of special case for that...


Although many systems do implement a special case that they flush stdout's
buffer when you read from stdin, it is still required on some systems so
it's a good idea to include the fflush(stdout) when writing portable code.


Which systems require the flush?

Jeremy.
Nov 14 '05 #15
"Jeremy Yallop" <je****@jdyallop.freeserve.co.uk> wrote in message
news:sl*******************@maka.cl.cam.ac.uk...
Although many systems do implement a special case that they flush stdout's buffer when you read from stdin, it is still required on some systems so
it's a good idea to include the fflush(stdout) when writing portable
code.
Which systems require the flush?


It's not required by 'systems', but by the language
standard.

-Mike
Nov 14 '05 #16
Mike Wahler wrote:
"Jeremy Yallop" <je****@jdyallop.freeserve.co.uk> wrote in message
news:sl*******************@maka.cl.cam.ac.uk...
> Although many systems do implement a special case that they flush stdout's > buffer when you read from stdin, it is still required on some systems so
> it's a good idea to include the fflush(stdout) when writing portable

code.

Which systems require the flush?


It's not required by 'systems', but by the language
standard.


No. The intent of the standard is exactly the opposite.

5.1.2.3
The input and output dynamics of interactive devices shall take
place as specified in 7.19.3. The intent of these requirements is
that unbuffered or line-buffered output appear as soon as possible,
to ensure that prompting messages actually appear prior to a
program waiting for input.

7.19.3
Furthermore, characters are intended to be transmitted as a block
to the host environment when a buffer is filled, when input is
requested on an unbuffered stream, or when input is requested on a
line buffered stream that requires the transmission of characters
from the host environment.

This comes up rather often: see Chris Torek's article
<news:c3*********@enews4.newsguy.com> from a few days ago for an
example.

Also, your news client is munging quoted text. Could you fix it,
please?

Jeremy.
Nov 14 '05 #17

On Thu, 1 Apr 2004, Leor Zolman wrote:

On Thu, 1 Apr 2004 02:54:31 -0500 (EST), Arthur J. O'Dwyer wrote:

Now, just a minute there! I'll grant you that scanf is less than
completely useful for *complex* validation, but *serious* validation
can indeed be performed, if you're willing to put up with the syntax.
I like scanf. :-)


I think the way it ignores leading newlines alone is enough to justify
dispensing with it for interactive use. Do you really want to have to
include text such as "If you press Enter first and nothing happens, don't
keep wailing on the Enter key! Try something /else/!" as part of your
prompt?


That's not intrinsic behavior of 'scanf' in general, but of the '%d'
and other format specifiers. The only reason my code ignores leading
whitespace (including '\n') is because I told it to. If you want to
get rid of the leading-whitespace-gobbler, you just remove the whitespace-
gobbling format specifier from the format string. That is, change
if (1 != scanf(" %4[0123456789]", buffer)) {


to

if (1 != scanf("%4[0123456789]", buffer)) {

or if you're really stubborn and clever,

scanf("%*[\t ]");
if (1 != scanf("%4[0123456789]", buffer)) {

This *must* be two separate 'scanf' invocations, though; if you run the
format specifiers together, it *demands* leading whitespace, which is
certainly not what we want! :)

-Arthur

Nov 14 '05 #18
On Thu, 1 Apr 2004 17:21:35 -0500 (EST), "Arthur J. O'Dwyer"
<aj*@nospam.andrew.cmu.edu> wrote:

On Thu, 1 Apr 2004, Leor Zolman wrote:

On Thu, 1 Apr 2004 02:54:31 -0500 (EST), Arthur J. O'Dwyer wrote:
>
> Now, just a minute there! I'll grant you that scanf is less than
>completely useful for *complex* validation, but *serious* validation
>can indeed be performed, if you're willing to put up with the syntax.
>I like scanf. :-)


I think the way it ignores leading newlines alone is enough to justify
dispensing with it for interactive use. Do you really want to have to
include text such as "If you press Enter first and nothing happens, don't
keep wailing on the Enter key! Try something /else/!" as part of your
prompt?


That's not intrinsic behavior of 'scanf' in general, but of the '%d'
and other format specifiers. The only reason my code ignores leading
whitespace (including '\n') is because I told it to. If you want to
get rid of the leading-whitespace-gobbler, you just remove the whitespace-
gobbling format specifier from the format string. That is, change
> if (1 != scanf(" %4[0123456789]", buffer)) {


to

if (1 != scanf("%4[0123456789]", buffer)) {


Ha! I must admit I had to stare at that new version for about 30 seconds
before I noticed the difference. I honestly didn't know you could do that
with scanf (If my own implementation of scanf from BDS C did that right, I
don't remember ever consciously thinking about it). So that's good to
know, and one point back to scanf's corner.
Thanks,
-leor

--
Leor Zolman --- BD Software --- www.bdsoft.com
On-Site Training in C/C++, Java, Perl and Unix
C++ users: Download BD Software's free STL Error Message Decryptor at:
www.bdsoft.com/tools/stlfilt.html
Nov 14 '05 #19
In <7H******************@newsread2.news.pas.earthlink .net> "Mike Wahler" <mk******@mkwahler.net> writes:
"Leor Zolman" <le**@bdsoft.com> wrote in message
news:56********************************@4ax.com.. .
>> printf("Please enter a year: ");
>
>Here you need to flush the stdout buffer to ensure that the prompt is
>displayed to the screen before you wait for user input.
> fflush(stdout);


Is that actually required for stdout if you then pause to read from stdin?


Yes, if you want to guarantee the output appears before
the input request.
Where'd I get the impression there was some sort of special case for
that...


Probably from C++, where cin/cout are 'tied', causing
the output to appear first automatically.


Why not from the C standard itself?

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #20
In <66********************************@4ax.com> Leor Zolman <le**@bdsoft.com> writes:
don't remember ever consciously thinking about it). So that's good to
know, and one point back to scanf's corner.


In competent hands, scanf is a very powerful beast. Could have been even
better if the committee tried harder (the * feature of printf conversion
specifications is sometimes badly needed).

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #21

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

Similar topics

2
by: atreide_son | last post by:
hello all... yes i'm a newbie and i need help. i have an assignment due for class, but I don't know i'm stuck and can't get out from under myself. here's the focus of the program: Write...
15
by: Buck Rogers | last post by:
Hi guys! Task 1: Write a program which presents a menu with 5 options. The 5th option quits the program. Each option should execute a system command using system(). Below is my humble...
8
by: drose0927 | last post by:
Please help! I can't get my program to exit if the user hits the Escape button: When I tried exit(EXIT_SUCCESS), it wouldn't compile and gave me this error: Parse Error, expecting `'}''...
38
by: Red Dragon | last post by:
I am self study C student. I got stuck in the program below on quadratic equation and will be most grateful if someone could help me to unravel the mystery. Why does the computer refuse to execute...
27
by: SK | last post by:
Hi I am trying to teach myself how to program in C. I am a physician hoping to be able to help restructure my office. Anyhow, I amhoping that the porblem I am having is simple to those much more...
83
by: deppy_3 | last post by:
Hi.I am started learning Programm language C before some time.I am trying to make a programm about a very simple "sell shop".This programm hasn't got any compile problem but when i run it i face...
6
by: toch3 | last post by:
i am writing a c program that is basically an address book. the only header we are using is #include<stdio.hwe are to use a global array, loops, and pointers. we are to have a menu at the...
22
by: Amali | last post by:
I'm newdie in c programming. this is my first project in programming. I have to write a program for a airline reservation. this is what i have done yet. but when it runs it shows the number of...
5
by: shanti | last post by:
hai, i have developed a c-code to push integers into a stack (an array). in the program there are three inputs which has to be given through keyboard. the inputs are "choice", "option","S_R_NO"...
2
by: memo | last post by:
hi im in a trouble with c++ i made a project with c but icant convert c ++ here is the code with c #include<stdio.h> #include<stdlib.h> #include <conio.h>
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.