尝试从键盘读取用户输入的字符串并将其分配给一个数组。 它仍然令人困惑。
还知道这个程序中的 char ch = 97 是什么吗? 谢谢。
#include<stdlib.h>
int main()
{
int i = 0;
int j = 0;
int count[26]={0};
char ch = 97;
char string[100]="readmenow";
for (i = 0; i < 100; i++)
{
for(j=0;j<26;j++)
{
if (tolower(string[i]) == (ch+j))
{
count[j]++;
}
}
}
for(j=0;j<26;j++)
{
printf("\n%c -> %d",97+j,count[j]);
}
}
最佳答案
要读取用户输入,请执行以下操作:
#include <stdio.h> // for fgets
#include <string.h> // for strlen
fgets(string,sizeof(string),stdin);
string[strlen(string)-1] = '\0'; // this removes the \n and replaces it with \0
确保包含正确的标题
还有 ch= 97
;与执行 ch = 'a';
编辑:
scanf
非常适合将输入读取为字符串,只要该字符串没有空格即可。 fgets
好得多
编辑 2
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
int i=0,j=0;
char input[50]; // make the size bigger if you expect a bigger input
printf("Enter string = ");
fgets(input,sizeof(input),stdin);
input[strlen(input)-1] = '\0';
int count[26]={0};
for (i = 0; i < strlen(input); i++)
{
for(j=0;j<26;j++)
{
if (tolower(input[i]) == ('a'+j))
{
count[j]++;
}
}
}
for(j=0;j<26;j++)
{
printf("\n%c -> %d",'a'+j,count[j]);
}
return 0;
}
输出: $./测试
Enter string = this is a test string
a -> 1
b -> 0
c -> 0
d -> 0
e -> 1
f -> 0
g -> 1
h -> 1
i -> 3
j -> 0
k -> 0
l -> 0
m -> 0
n -> 1
o -> 0
p -> 0
q -> 0
r -> 1
s -> 4
t -> 4
u -> 0
v -> 0
w -> 0
x -> 0
y -> 0
z -> 0
关于c - 如何读取用户输入的字符串并将其存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19749213/