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

用fgets() 从键盘输入是否要比最大字数少2个才好

2013-06-26 
用fgets() 从键盘输入是不是要比最大字数少2个才好?因为fgets()要读取换行符,而且因为字符串有空字符,所以

用fgets() 从键盘输入是不是要比最大字数少2个才好?
因为fgets()要读取换行符,而且因为字符串有空字符,所以最大输入字符数是要比设定的字符串长度少2个字节。如下面的程序。

#include "stdafx.h"
#include "stdio.h"
#include "string.h"
#include "stdlib.h"

int main(void)
{
char str3[4];
char str4[4];

fgets(str3, 4,stdin);
fputs(str3, stdout);
printf("%d\n", strlen(str3));
printf("%d\n", sizeof(str3));

puts("\n");

gets(str4);
puts(str4);
printf("%d\n", strlen(str4));
printf("%d\n", sizeof(str4));

return 0;
}

当我str3输入ab,且str4也输入ab时,得到的结果是
ab
ab
3
4


ab
ab
2
4
Press any key to continue
显然str3有strlen为3,显示包括了换行符。当我再次编译将str3输入abc时,得到的结果是

abc
abc3
4



0
4
Press any key to continue

所以,我觉得如果是用fgets输入字符最好是比本身字节长度最少要少2个字节,对吗?

[解决办法]
擦,打错了!补充  LS:
str3已经定义成了长度是4的数组,所以sizeof(str3)为4,即总空间大小。 

因为在数组未满之前,如果读到一个‘\n’或者EOF,就会结束读入,并且‘\n’也会被保留。

楼主看看这个:
#include "stdio.h"
#include "string.h"

int main(void)
{   
char str3[4];  
    
    fgets(str3, 4,stdin); 

printf("%d\n", strlen(str3));
    printf("%d\n", sizeof(str3)); 
      
 
return 0;
}


两个对比一下····看看有什么不同
[解决办法]
嗯,最好这样,否则不会读入换行符。。
[解决办法]
仅供参考
#include <stdio.h>
#include <string.h>
#define MAXLEN 1000
char ln[MAXLEN];
FILE *f;
int i,z;
int b,n,L;
int main(int argc,char **argv) {
    if (argc<2) {
        printf("Usage:%s fullpathfilename.ext\nget total blank/non-blank/total linenumbers.\n",argv[0]);
        return 1;
    }
    f=fopen(argv[1],"r");
    if (NULL==f) {
        printf("Can not open file [%s]!\n",argv[1]);
        return 2;
    }
    z=0;
    b=0;
    n=0;
    L=0;
    while (1) {
        if (NULL==fgets(ln,MAXLEN,f)) break;
        L=strlen(ln);
        if ('\n'==ln[L-1]) {
            if (0==z) {
                for (i=0;i<L-1;i++) {


                    if (!(' '==ln[i] 
[解决办法]
 '\t'==ln[i])) break;
                }
                if (i<L-1) z=1;//当前行不是空行
            }
            if (0==z) b++; else n++;
            z=0;
        } else {
            if (0==z) {
                for (i=0;i<L;i++) {
                    if (!(' '==ln[i] 
[解决办法]
 '\t'==ln[i])) break;
                }
                if (i<L) z=1;//当前行不是空行
            }
        }
    }
    fclose(f);
    if (L>0 && '\n'!=ln[L-1]) {
        if (0==z) b++; else n++;//最后一行末尾无'\n'也计算
    }
    printf("File:[%s] total blank/non-blank/total linenumbers is %d/%d/%d\n",argv[1],b,n,b+n);
    return 0;
}


[解决办法]
char *fgets(char *s, int n, FILE *stream)
fgets reads at most the next n-1 characters into the array s, stopping if a newline is encountered; the newline is included in the array, which is terminated by '\0'. fgets returns s, or NULL if end of file or error occurs.
[解决办法]
FGETS()会读入回车健。

热点排行