pta b1014 福尔摩斯的约会 (20分)

  • fgets(char *,int x,file *)

(1)一般若读取的字符数小于X-1,且使用换行来结束本行的输入,且换行符也保存在str中;

   fgets(str[i],61,stdin);

    输入59个字符,则str[59] == '\n' 成立;

    输入40个字符,则str[40] == '\n'成立;

(2)当等于X-1时,换行符不会保存在str中,但是存在于输入缓冲中,

    输入60个字符,则str[60] == '\0'成立,换行符会保留在输入buffer中;

    输入66个字符,但str只需要60个,str[60] == '\0'成立,其他6个字符及换行符会保留在输入buffer中;


第一步,fgets(str[i],61,stdin);最多将60个字符放入str[i],但是问题是当恰好输入60个及以上字符时,换行符会保留在输入缓冲中,所以必须清理不需要的字符

第二步,定义了闲置的一个字符数组来吸收第一步中的换行符及其他超出60个字符外的其他字符,为了不影响下一行的输入。

   char str[4][61] = {};
    char tmp[60] = {};
    for(int i = 0; i < 4; i++){
        fgets(str[i],61,stdin);
        if(strlen(str[i]) == 60){
            fgets(tmp,60,stdin);
        }
    }
    int len[4] = {0};
    for(int i = 0; i < 4; i++){
        len[i] = strlen(str[i]);
        int tmp = len[i];
        if(str[i][tmp-1] == '\n'){
            str[i][tmp-1] = '\0';
            len[i] = strlen(str[i]);
        }
    }

参考文档:https://www.cnblogs.com/L-0x0b/p/10858518.html 

猜你喜欢

转载自www.cnblogs.com/hiwjw/p/12716818.html