C - scanf() vs gets() vs fgets()

前端 未结 7 1363
情话喂你
情话喂你 2020-11-22 16:38

I\'ve been doing a fairly easy program of converting a string of Characters (assuming numbers are entered) to an Integer.

After I was done, I noticed some very pecul

7条回答
  •  面向向阳花
    2020-11-22 17:08

    Try using fgets() with this modified version of your CharToInt():

    int CharToInt(const char *s)
    {
        int i, result, temp;
    
        result = 0;
        i = 0;
    
        while(*(s+i) != '\0')
        {
            if (isdigit(*(s+i)))
            {
                temp = *(s+i) & 15;
                result = (temp + result) * 10;
            }
            i++;
        }
    
        return result / 10;
    }
    

    It essentially validates the input digits and ignores anything else. This is very crude so modify it and salt to taste.

提交回复
热议问题