阅读使用scanf()的不好的线路? [英] Reading a line using scanf() not good?

查看:140
本文介绍了阅读使用scanf()的不好的线路?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

scanf(" %[^\n]",line);

我的一个朋友建议使用与fgets()来读取一行输入会比使用 scanf()的一个更好的主意如上声明。他是有道理的吗?

A friend of mine suggested that using fgets() to read a line as input would be a much better idea than using scanf() as in the statement above. Is he justified?

推荐答案

字符*与fgets(的char * str中,INT NUM,FILE *流); 是安全的使用,因为它避免缓冲区溢出问题,仅扫描 NUM-1 字符数。

char * fgets ( char * str, int num, FILE * stream ); is safe to use because it avoid buffer overflow problem, it scans only num-1 number of char.

从读取字符流,并将它们存储为C字符串str中,直到(NUM-1)个字符已读或达到或者换行或档案结尾,先发生者为准。

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

下面第二个参数 NUM 将被复制到str中的最大字符数(包括终止空字符)。

here second argument num is Maximum number of characters to be copied into str (including the terminating null-character).

例如,假设你的code字符串数组容量仅仅是 5 如下长字符。

For example suppose in your code a string array capacity is just 5 chars long as below.

 char str[5];
 fgets (str, 5, fp);  //5 =you have provision to avoid buffer overrun 

使用上述code,如果从 FP 长于 4 字符,<$ C $输入C>与fgets()将只读取第一个 4 字符,然后追加 \\ 0 ,并丢弃其它多余的输入字符,仅仅存储在海峡[] 的)。

Using above code, if input from fp is longer then 4 chars, fgets() will read just first 4 chars then appends \0 (, and discard other extra input chars, just stores five char in str[]).

scanf函数(%[^ \\ n],STR); 将读到 \\ n 不发现,如果输入的字符串长度超过 4 字符 scanf()的将导致的buffer溢出(如 scanf函数将尝试访问的内存超越最大指数 4 海峡[] )。

Whereas scanf(" %[^\n]",str); will read until \n not found and if input string is longer then 4 chars scanf() will cause of buffer overflow (as scanf will try to access memory beyond max index 4 in str[]).

这篇关于阅读使用scanf()的不好的线路?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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