我想输入文本和特定字符。 之后我想计算文本中包含多少个这些字符。
我的代码
#include <stdio.h>
#include <stdlib.h>
int counting(char text[], char character);
int main()
{
char text[20];
char character;
int a;
printf("Enter text!\n");
scanf("%s", text);
printf("Enter character!\n");
scanf("%s", character);
a= counting(text, character);
printf("Text contain %d character!\n", a);
}
以及计数功能
int counting(char text[], char character)
{
int i=0;
int counter=0;
while(text[i] != '\0')
{
if (text[i]==character)
{
counter++;
}
}
i++;
return counter;
}
错误:
最佳答案
读取字符的行需要是:
scanf(" %c", &character);
另外,
scanf("%s", text);
不安全。如果用户输入的字符串超过 19 个字符,您将写入未经授权的内存,这将导致未定义的行为。
使用
scanf("%19s", text);
关于c++ - 调用函数传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837716/