c - I'm finding the frequency of each letter, although it always returns 0 for all the letters
问题描述
int main (){
char string[100];
int c=0,count[26]={0},x;
gets(string);
while(string[c]!='\0'){
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++){
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
}
return 0;
}
Firstly, it gives me this error about get: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration] gets(string); And I don't know why doesn't work, although it makes sense.
解决方案
gets()
使用是有风险的。它会遭受缓冲区溢出,因为 gets() 不进行任何数组绑定测试。gets()
继续阅读,直到看到换行符。
尝试scanf("%99[^\n]", string);
代替您的代码gets(string);
。
试试这个修改后的代码。这将起作用:-
#include <stdio.h>
int main (){
char string[100];
int c=0,count[26]={0},x;
scanf("%99[^\n]", string);
while(string[c]!='\0'){
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++){
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
}
return 0;
}
另一种解决方案是使用fgets()
.
您可以使用fgets(string,100, stdin);
而不是 gets(string);
.
修改后的代码将是:-
#include <stdio.h>
int main (){
char string[100];
int c=0,count[26]={0},x;
fgets(string,100, stdin); // 100 is the Max Limit of array
while(string[c]!='\0'){
if (string[c] >= 'a' && string[c] <= 'z') {
x = string[c] - 'a';
count[x]++;
}
c++;
}
for (c = 0; c < 26; c++){
printf("%c occurs %d times in the string.\n", c + 'a', count[c]);
}
return 0;
}
推荐阅读
- rust - Rust 为 Arc 实现 Into 特征
到弧 - vue.js - IE / Edge上的VueJS v-slot中的对象解构
- javascript - 连接到 HTTP Tornado 服务器时出现 SSL 证书未知错误
- flutter - Flutter - 如何在错误时更改文本表单字段的边框
- asp.net - 如何在标签重定向中传递数据
- mysql - 无法弄清楚我的触发逻辑的问题?
- ruby - 使用 ruby 出错特殊字符 Google Sheets api v4
- alexa - Alexa 技能 - 测验
- c# - 在我的情况下,如何在 WPF TextBox 中使文本变为粗体?
- sql - 如何通过 Teradata 中的存储过程从 VT 返回数据?