/
如何优雅的将输入的字符和数字分开.cpp
112 lines (96 loc) · 1.56 KB
/
如何优雅的将输入的字符和数字分开.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# include <stdio.h>
# include <ctype.h>
# include <windows.h>
# include <string.h>
const size_t LENGTH = 50;
void eatspaces(void);
char *getname(char *name, size_t length);
bool getinteger(int *n);
bool isnewline(void);
int main(void)
{
int number;
char name[LENGTH];
printf("Enther a sequence of integers and alphabetic names:\n");
while(!isnewline())
{
if(getinteger(&number))
{
printf("number value = %d\n",number);
}
else if(strlen(getname(name,LENGTH)) > 0)
{
printf("name is:%s\n",name);
}
else
{
printf("Invalid input.\n");
return 1;
}
}
return 0;
}
void eatspaces()
{
char temp = 0;
while(isspace(temp = getchar()));
ungetc(temp,stdin);
}
bool isnewline(void)
{
char ch = 0;
if((ch = getchar()) == '\n')
{
return true;
}
else
{
ungetc(ch,stdin);
return false;
}
}
bool getinteger(int *n)
{
int value = 0;
int sign = 1;
char ch = 0;
eatspaces();
if((ch = getchar()) == '-')
{
sign = -1;
}
else if(isdigit(ch))
{
value = 10*value + (ch -'0');
}
else if(isalpha(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)
break;
}
name[count] = '\0';
if(count < length)
{
ungetc(ch,stdin);
}
return name;
}