请问,数字字符转换为数字存储,如何检测超出位数
											 程序代码:
程序代码:/* Program 10.7 Reading and unreading characters */
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
const size_t LENGTH = 50;
void eatspaces(void);
bool getinteger(int *n);
char *getname(char *name, size_t length);
bool isnewline(void);
int main(void)
{
    int number;
    char name[LENGTH];
    printf("Enter a sequence of integers and alphabetic names:\n");
    /*              序列         整数         拼音 */
    while(!isnewline())
        if(getinteger(&number))
        printf("\nInteger value:%8d", number);
    else if(strlen(getname(name, LENGTH)) > 0)
        printf("\nName: %s", name);
    else
    {
        printf("\nInvalid input.");
        return 1;
    }
    return 0;
}
// Function to check for newline
bool isnewline(void) //检测回车
{
    char ch = 0;
    if((ch = getchar()) == '\n')
       return true;//结束while()
    ungetc(ch, stdin);
    return false;
}
// Function to ignore spaces from standard input
void eatspaces(void) //略过空格
{
    char ch = 0;
    while(isspace(ch = getchar()));/*变元是空格或制表符 返回true*/
    //                 返回值是int
    ungetc(ch, stdin);
}
// Function to read an integer from standard input
bool getinteger(int *n)//数字字符串 转换
{
    eatspaces();//找到字符
    int value = 0;
    int sign = 1;
    char ch = 0;
    if((ch=getchar()) == '-')
        sign = -1;
    else if(isdigit(ch))//检测十进制数字字符
        value = 10*value + (ch - '0');//如何检测超出int 上限
    else if(ch != '+')
    {
        ungetc(ch, stdin);
        return false;
    }
    while(isdigit(ch = getchar()))
        value = 10*value + (ch - '0');
    ungetc(ch,stdin);
    *n = value*sign;
    return true;
}
char * getname(char *name, size_t length)
{
    eatspaces();
    size_t count = 0;
    char ch = 0;
    while(isalpha(ch=getchar()))//确认字符为英文字母
    {
        name[count++] = ch;
        if(count == length-1)
            break;
    }
    name[count] = '\0';
    if(count < length-1)
        ungetc(ch, stdin);//这是在预防什么?
    return name;
}
//12                          Jack Jim 234 Jo Janet 99 88书中的例子请问
1,数字字符转换为数字存储,如何检测超出位数?(第二个bool函数)
2,最后一个函数的最后一个if()是怎样的逻辑?
3,如果存储的数值,超过变量类型的极限值,那么之后变量的状态是什么样?是存储了极限值,还是丢失了某一位呢?
4,如果只输入回车,程序就会结束,这也不是预期结果(个人理解逻辑为while(!true);else if(0>0);else if return1 才对啊)
而且如果输入了空格,再输入回车,程序就不会结束,是什么道理?
预谢!
[此贴子已经被作者于2019-5-4 14:32编辑过]



 
											





 
	    

 
	


