无法将单个Char与Chars数组进行比较

时间:2018-04-08 01:06:55

标签: c char compare

我一直得到错误:“下标值既不是数组也不是指针也不是矢量”我第14行的代码。看起来它应该能够将数组中的值与char进行比较,因为它们是两个原始数据,但我似乎无法做到正确:

#include <stdio.h>
#include <string.h>

char str[80];
char ch;
int cnt =0;

int suffix ( str, ch) {

int i=0;

while (strchr(str+i, ch) != NULL){

    if (ch == str[i] ){
        printf("\n %s \n", str+i);
        cnt += 1;

    }

    i++;        

}
return cnt;
}

int main() {


printf("\n Please type a single character and then press ENTER: \n");
ch = getchar();
printf("\n You have typed in the character \" %c \".\n", ch);

printf("\n Now please enter a string. Press ENTER to confirm: \n");
scanf("%s", str);
printf("\n The String you typed in is: %s.", str);

suffix(str, ch);
printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
return 0;

}

1 个答案:

答案 0 :(得分:2)

问题在于你宣布这样的功能:

int suffix ( str, ch)
{
    ...
}

没有告诉编译器strch的类型。所以编译器假定 它们是int,您无法在[]上使用int。你必须申报 像这样的功能

int suffix(char *str, char ch)
{
    ...
}

为什么要将strchcnt声明为全局变量?有 绝对没有理由。

所以程序看起来应该是这样的:

#include <stdio.h>
#include <string.h>

// const char is even better, because you are not modifying the string
int suffix (const char *str, char ch) {

    int cnt = 0;
    int i=0;

    while (strchr(str+i, ch) != NULL){

        if (ch == str[i] ){
            printf("\n %s \n", str+i);
            cnt += 1;

        }

        i++;        

    }
    return cnt;
}

void clean_stdin(void)
{
    int ch;
    while((ch = getchar()) != '\n' && ch != EOF);
}

int main() {

    int ch;
    int cnt;
    char str[100];

    printf("\n Please type a single character and then press ENTER: \n");
    ch = getchar();
    printf("\n You have typed in the character \" %c \".\n", ch);

    clean_stdin(); // to get rid of the newline in the input buffer
                   // or if the user typed more than a single character

    printf("\n Now please enter a string. Press ENTER to confirm: \n");
    scanf("%99s", str);
    printf("\n The String you typed in is: %s.", str);

    cnt = suffix(str, ch);
    printf("The character \" %c \" appeares %d times in the string. \n", ch, cnt);
    return 0;
}