首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

用gets(str)取用户输入的时候,怎么限制输入字符串的长度不要超过str的长度

2012-02-04 
用gets(str)取用户输入的时候,如何限制输入字符串的长度不要超过str的长度?如题,比如str是个长度为10的字

用gets(str)取用户输入的时候,如何限制输入字符串的长度不要超过str的长度?
如题,比如str是个长度为10的字符串,
如果用户输入了一串长度超过10的很长的字符串的话,会报异常的吧。
如何判断或限制输10个以内的字符呢?

[解决办法]
不要用gets,它过时了。它曾经制造了一个大的bug.
用fgets吧。。它是安全的。。
char line[125];
fgets(line,sizeof(line),stdin)
[解决办法]
这是C&C++.Programmers.Reference 对gets()的说明:
There is no way to limit the number of characters that gets( ) will read, which means that the array pointed to by str could be overrun. Thus, this function is inherently dangerous. Its use should be limited to sample programs or utilities for your own use. It should not be used for production code.

C语言的底层就很大程度地表现在这里,仅仅通过指针来处理问题,因为为了取代汇编而不得不这样做。
你可以先把输入放入一个你认为足够大的缓冲区中,再测试字符个数,恐怕C的stdin不能为你提供这种服务,你只能自己建缓冲了,不过C++的istream可以,若你用C++的话,可以直接用istream的成员函数get()。

[解决办法]
fgets

热点排行