关于“scanf”的简单问题 [英] a simple question about about "scanf"

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

问题描述

 #includestdio.h
void main()
{
char a [20];
scanf(%s,a);
printf(%s,a);
}





我想输入少于20个字符,如何控制我输入的数字?

如果数量超过20,程序应该给我一个警告,我想知道怎么做,谢谢。

解决方案

使用 scanf()和字符串,您应该始终传递宽度以指定最大值。要存储的字符数(传递一个小于char数组的大小以存储终止 NULL char)。所以最大。 20个字符使用:

  char  a [ 21 ]; 
scanf( %20s,a);



要获得输入的字符数,请使用 strlen()函数。要在输入太多字符时显示警告,请再扫描一个字符并比较最终字符串长度:

  char  a [ 22 ]; 
scanf( %21s,a);
if (strlen(a)> 20
{
// 在此处显示警告
}


您可以使用宽度说明符(请参阅 MSDN文档中的安全说明 [ ^ ]),例如

 scanf( %19s, a); 





(并且始终检查 scanf 结果)


请检查答案 - 如何限制C中的scanf功能,以便在输入太长时打印错误? [ ^ ]和其他答案。



比KS ...

#include "stdio.h"
void main()
{
	char a[20];
	scanf("%s",a);
	printf("%s",a);
}



I want to input less than 20 characters, how to control the number I input?
if the number is more than 20, the program should give me a warn, I want to know how to do this,Thank you.

解决方案

With scanf() and strings, you should always pass the width to specify the max. number of chars to be stored (pass one less than the size of the char array to store the terminating NULL char). So with max. 20 chars use:

char a[21];
scanf("%20s",a);


To get the number of chars entered, use the strlen() function afterwards. To show a warning when too much chars has been entered, allow one more character to be scanned and compare the final string length:

char a[22];
scanf("%21s",a);
if (strlen(a) > 20)
{
    // show warning here
}


You may use the width specifier (see the security note in the MSDN documentation[^]), e.g.

scanf("%19s",a);



(and always check scanf result)


Please check Answer - How to limit scanf function in C to print error when input is too long?[^] and other answers too.

Thanks...


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

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