天天看點

C語言之字元串輸入(通用無Bug)

看代碼:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *MyGetStr1(char *buf, int size);
char *MyGetStr2(char *buf, int size);

char *MyGetStr1(char *buf, int size)
{
    char    ch;
    int     count = 0;

    if( (buf == NULL) || (size <= 0) )
    {
        return NULL;
    }

    memset(buf, 0, size);

    ch = getchar();

    while(ch != '\n')   //Until '\n' end
    {
        if( count < size-1)
        {
            buf[count] = ch;
        }
        count++;
        ch = getchar();
    }

    return buf;
}


char *MyGetStr2(char *buf, int size)
{
    int     len = 0;

    if( (buf == NULL) || (size <= 0) )
    {
        return NULL;
    }

    fgets(buf, size, stdin);
    len = strlen(buf);

    if(buf[len-1] != '\n')
    {
        while (getchar() != '\n'){}     //清除輸入多餘的字元
    }
    else
    {
        buf[len-1] = '\0';              //自動添加結束符
    }

    return buf;
}
           

繼續閱讀