c++ - 调用函数传递数组

标签 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);
    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;
}


错误:
enter image description here

最佳答案

读取字符的行需要是:

scanf(" %c", &character);

另外,

scanf("%s", text);

不安全。如果用户输入的字符串超过 19 个字符,您将写入未经授权的内存,这将导致未定义的行为。

使用

scanf("%19s", text);

关于c++ - 调用函数传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24837716/

相关文章:

c++ - 复制构造函数和运算符重载 : C++

c++ - 最小化后窗口不显示(最大化)

c++ - 为 Unicode 和 ANSI 重载 toString

c - 栈和堆的区别

arrays - 如何循环遍历 JSONb 字段中包含的数组?

c++ - 从返回基类指针的派生类对象调用方法

c - 为什么这是一个非法的常量表达式?

c - 使用 C 和 Stellaris Launchpad 的意外除法/乘法行为

javascript - 将数据从 JavaScript 数组插入到另一个数组

ios - 正在从解析数据库检索数据