FGETS最大尺寸读 [英] fgets maximum size read

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

问题描述

使用与fgets 来输入一个字符串,我有相关的字符串的长度读疑惑。

例如,请考虑下面的程序。

 字符海峡[50];
INT I;
INT LEN;
的printf(请输入名称:\\ n);
与fgets(STR,11,标准输入);
LEN = strlen的(STR);
的printf(LEN数:%d \\ n,LEN);


  1. 如果我输入 123456789 的strlen 10给出了


  2. 如果我输入 1234567890 的strlen 再给予10 ??


我觉得的strlen 正在考虑换行也为字符串的长度。我对么?
(我用换行符作为字符串的一部分理解与fgets

这有什么错(2)在那里我准确输入10个字符,下面的字符串长度应该是11吧? 10 + 1(用于换行符)= 11


解决方案

与fgets 读取至多更少的字符比长度参数给出,和确实保留换行符作为输入的一部分 - 只要换行是第一部分(长 - 1)。字符

因此​​,在你第一种情况下,假设 123456789 后跟一个换行符,与fgets 已经阅读9个字符,包括换行,产生10字符串长度;在第二种情况下,与fgets 将读取10个字符后停止 1234567890 ,产生10字符串的长度。

Using fgets to input a string, I have doubts related to length of string read.

For example, consider the following program.

char str[50];
int i;
int len;
printf("Enter name:\n");
fgets(str,11,stdin);
len = strlen(str);
printf("len :  %d\n",len);

  1. If I enter 123456789, strlen gives 10.

  2. If I enter 1234567890, strlen given is 10 again ??

I think strlen is considering newline also for string length. Am I correct? (I understand fgets using newline as part of string)

What's wrong with (2) where I enter exactly 10 characters, Here string length should be 11 right? 10 + 1 (for newline) = 11

解决方案

fgets reads at most 1 fewer characters than the length argument given, and does retain the newline as part of the input - so long as the newline is part of the first (length - 1) characters.

So in your first case, assuming that 123456789 is followed by a newline, fgets has read 9 characters including the newline, yielding a string length of 10; in your second case, fgets will stop after reading the 10 characters 1234567890, yielding a string length of 10.

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

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