#5
by かずま » 6年前
scanf の "%s" で入力すると、文字列に空白を含めることができません。
空白も含めたいなら、fgets で 1行入力するとよいでしょう。
最後の改行文字を削除するのに strchr が使えるので、string.h を
使うことになります。
分類表を「数字」ではなく、「数値」にすると、
n[t[c] - '0']++; が n[t[c]]++; と簡単になります。
コード:
#include <stdio.h> // fgets, printf
#include <string.h> // strchr
const char t[256] = { // 0:other, 1:digit, 2:uppercase, 3:lowercase
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,
0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
};
int main(void)
{
char s[256], *p;
unsigned char c;
int n[4] = { 0 }; // [0]other, [1]digit, [2]uppercase, [3]lowercase
printf("string=> ");
if (!fgets(s, sizeof s, stdin)) return 1;
p = strchr(s, '\n');
if (p) *p = '\0';
for (int i = 0; c = s[i]; i++) n[t[c]]++;
printf(" lowercase=>%d uppercase=>%d digit=>%d other=>%d\n",
n[3], n[2], n[1], n[0]);
}
scanf の "%s" で入力すると、文字列に空白を含めることができません。
空白も含めたいなら、fgets で 1行入力するとよいでしょう。
最後の改行文字を削除するのに strchr が使えるので、string.h を
使うことになります。
分類表を「数字」ではなく、「数値」にすると、
n[t[c] - '0']++; が n[t[c]]++; と簡単になります。
[code]
#include <stdio.h> // fgets, printf
#include <string.h> // strchr
const char t[256] = { // 0:other, 1:digit, 2:uppercase, 3:lowercase
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,
0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,
0,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,
};
int main(void)
{
char s[256], *p;
unsigned char c;
int n[4] = { 0 }; // [0]other, [1]digit, [2]uppercase, [3]lowercase
printf("string=> ");
if (!fgets(s, sizeof s, stdin)) return 1;
p = strchr(s, '\n');
if (p) *p = '\0';
for (int i = 0; c = s[i]; i++) n[t[c]]++;
printf(" lowercase=>%d uppercase=>%d digit=>%d other=>%d\n",
n[3], n[2], n[1], n[0]);
}
[/code]