帮助scanf [英] Help with scanf

查看:64
本文介绍了帮助scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,使用scanf将日期作为输入。我想要验证用户是否输入了

年的全部4位数。我该怎么做呢?我知道printf的返回值是

打印字符数;所以,如果我能以某种方式得到我的年份

变量来存储前导零,我可以运行一个支票:


int dummy = 0;


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


if(dummy!= 4)

{

...做点什么...

}

解决方案

2004年3月31日19:54:06 -0800, ma****@tamu.edu (Sivarn)写道:

我正在编写一个程序,使用scanf将日期作为输入。我想确认用户输入的是完整的4位数。我该怎么做呢?我知道printf的返回值是打印字符的数量;所以,如果我能以某种方式获得我的年份
变量来存储前导零,我可以运行一个检查:

int dummy = 0;

dummy = printf (%d,年);

if(dummy!= 4)
{
...做点什么......
}



等一下......你开始询问scanf,你说你想要b $ b验证输入吗?那么我肯定你不想打印价值

只是为了能够验证用户输入,对吧?


你当然不必。让我们继续使用scanf,因为那是'

你怎么说你这样做(但是如果你需要,scanf基本没用

严重输入验证。稍后会详细介绍......):


int count;

int year;

count = scanf (%d,& year);


请注意,您必须提供&在一年,因为scanf必须知道/ where /

来放置值。 count会告诉你有多少项目被扫描;如果用户没有输入数字,它可以是
为0。所以让我们测试一下:


if(count!= 1)

{

printf("输入错误)你输了。\ n");

退出(1);

}


(当然你可能会选择除了退出这里以外的事情。)


那么,如何测试4位数?好吧,我能想到的最简单的方法是

只测试有效(或无效)的范围:


if(year< 1900 ||年份> 2030)/ *或其他* /

{

printf(糟糕的一年。你不在这里。\ n);

退出(1);

}


如果您/确实/想要任何4位数字,只需测试它介于

1000和9999之间。


这样可以解决这个问题。现在我们可以改善输入。 sscanf是一个很难处理的皇家工作,因为如果用户只是一直按下输入,它就会快速回复空白行直到世界末日(它忽略了领先的空白,

包括换行符)。如果用户按下一个字母,当scanf是

寻找一个数字时,那个字母在输入流上持续/ next /

你尝试阅读的时间一个数字,进一步造成严重破坏。


最好强制输入一行,然后处理它。我喜欢使用

fgets将一行读入缓冲区,然后使用sscanf进行转换。

sscanf与scanf非常相似,但是它从一个读取输入字符串缓冲区而不是标准输入的
。把所有这些与一些

重新提示逻辑放在一起,这里有一个程序给你:


#include< stdio.h>


int main()

{

int year;

char buffer [100];


而(1)

{

printf(请输入一年:);

fgets(buffer,100,stdin);

if(sscanf(buffer,"%d",& year)!= 1)

printf(" ;那不是数字!再试一次.... \ n");

else if(year< 1900 || year> 2030)

printf(糟糕的一年!必须在1900年到2030年之间。

再试一次...... \ n);

else

休息;

}


printf(成功!你的年份是%d \ n,年份);


返回0;

}


这是你现在可以扩展以支持尽可能多的处理的东西
你可以随意输入
输入,而无需运行int你可以使用scanf来获得一大堆问题。


祝你好运,

-leor


-

Leor Zolman --- BD软件--- www.bdsoft.com

C / C ++,Java,Perl和Unix的现场培训

C ++用户:下载BD软件这是免费的STL错误消息解密器:
www.bdsoft。 com / tools / stlfilt.html


2004年4月1日星期四04:39:57 GMT,Leor Zolman< le ** @ bdsoft.com> ;写道:

这样就可以解决这个问题。现在我们可以改善输入。 $ sscanf是一种使用的主要痛苦




这应该是:/ scanf /是一种皇家的痛苦......哎呀。

-leor


-

Leor Zolman --- BD软件--- www.bdsoft.com

C / C ++,Java,Perl和Unix的现场培训

C ++用户:下载BD Software的免费STL错误消息解密器:
www.bdsoft.com/tools/stlfilt.html


" Leor Zolman" <乐** @ bdsoft.com>写道:

if(count!= 1)
{
printf(输入错误。你输了。\ n);
退出(1) ;
}


1不是便携式退出代码(终止状态);它可能有意想不到的

效果。如果要指示失败,请使用宏明确地执行此操作

EXIT_FAILURE。唯一的便携式退出代码是0,EXIT_SUCCESS和

EXIT_FAILURE。 EXIT_SUCCESS的值可能为零,也可能不为零,但

效果相同。

退出(EXIT_FAILURE);

EXIT_FAILURE定义于< stdlib.h中>你应该已经包含了退出函数本身的
。它可能会扩展到1或任何其他值

而不是零。


此外,请不要在新闻组中发布标签。缩进应使用

空格。


[...]

#include< stdio.h>

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

while(1)
{
printf(请输入一年:);


在这里你需要刷新标准输出缓冲区以确保在等待用户输入之前在屏幕上显示提示



fflush(stdout);

fgets(buffer,100,stdin);


我会避免使用魔法数字并检查成功/失败

if(fgets(buffer,sizeof buffer,stdin)== NULL)

{

printf(读取输入时出现问题。\ n);

退出(EXIT_FAILURE);

}


此时如果用户输入的数字超出了int范围,则sscanf的

行为将是未定义的。这是在继续之前验证

输入的好点。

if(strlen(buffer)!= 5 || strspn(buffer," 0123456789 \ n" )!= 5)

{

printf(那不是四位数!再试一次...... \ n);

}

else

if(sscanf(buffer,"%d",& year)!= 1)
printf("那不是数字!再试一次.... \ n");
如果(年< 1900 ||年> 2030)
printf(坏年!必须是在1900年到2030年之间。
再试一次...... \ n;
其他
打破;
}

printf( 成功!你的年份是%d \ n,年);

返回0;
}




- -

Simon。


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...
}

解决方案

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


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


"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.


这篇关于帮助scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆