fgets后Strlen给出了不正确的输出 [英] Strlen gives an incorrect output after fgets

查看:72
本文介绍了fgets后Strlen给出了不正确的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用fgets读取了一个字符串.它可以正确打印,但是如果我尝试使用strlen或一会儿直到NULL来输出长度,它将返回一个错误的值.fgets不会以NULL结尾字符串吗?

I read a string using fgets. It prints correctly but if i try to output the length using a strlen or a while until NULL it returns a bad value. Does fgets not end the string with NULL?

char word[256];
fgets(word, sizeof(word), stdin);
while(word[i])
    i++;
printf("%d",i);

对于字符串aba,它输出40.

For the string aba it outputs 40.

推荐答案

函数 fgets 还在字符串中包含换行符.因此函数 strlen 会计算该符号.

Function fgets also includes the new line character in the string. So function strlen counts this symbol.

根据C标准

2 fgets函数最多读取少于n从流指向的流中指定的字符s指向的数组.在换行符(保留)或文件末尾.空值在最后一个字符读入后立即写入字符数组.

2 The fgets function reads at most one less than the number of characters specified by n from the stream pointed to by stream into the array pointed to by s. No additional characters are read after a new-line character (which is retained) or after end-of-file. A null character is written immediately after the last character read into the array.

这篇关于fgets后Strlen给出了不正确的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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