C++ 调用传递数组的函数';s
我想输入文本和特定字符。 在那之后,我想数一数文本中包含了多少个字符 我的代码C++ 调用传递数组的函数';s,c++,c,arrays,function,C++,C,Arrays,Function,我想输入文本和特定字符。 在那之后,我想数一数文本中包含了多少个字符 我的代码 #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);
#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);
}
错误:
读取字符的行需要是:
scanf(" %c", &character);
而且
这是不安全的。如果用户输入的字符串长度超过19个字符,您将在未经授权的内存中写入,这将导致未定义的行为
使用
在函数
int计数(…)
在你的中需要i++
,而..loop
你有两个问题
1) 您正在以字符串形式读取特定字符,因此必须更改scanf(“%s”,字符)代码>到scanf(“%c”,字符)代码>
2) 在函数counting()
i++
中需要在while循环中,这样你就不会进入无限循环。@Jayesh它不工作,它显示的是我,错误图片:@R Sahu整个代码现在看起来像这样,但仍然不工作它显示的是这样我甚至无法进入循环character@t3cho它被正确地执行了。您对字符的输入是什么?在屏幕截图中,我看到您没有输入任何字符。@t3cho,您使用的是“%c”
,而不是“%c”
。额外的空间是必要的,这样您就不会最终读取上一行的'\n'
。
scanf(" %c", &character);
scanf("%s", text);
scanf("%19s", text);
while(text[i] != '\0')
{
if (text[i]==character)
{
counter++;
}
}
i++;