二进制%的操作数无效(有.char *。和.int。)

时间:2013-05-17 03:04:49

标签: c

我是C编程的新手,所以这可能是一个愚蠢的问题......但是我收到了以下错误:

45: error: invalid operands to binary % (have .char*. and .int.)
45: error: expected .). before string constant

第45行是第二个printf函数

一些信息: charsInWord和indexOf都返回一个int值

int main() 
{ 
    char word [20]; 
    char c;

    printf("Enter a word and a character separated by a blank ");
    scanf("%s %c", word, &c);

    printf("\nInput word is "%c". contains %d input character. Index of %c in it is %d\n", word, charsInWord(word), c, indexOf(word, c));

    return 0;
}

5 个答案:

答案 0 :(得分:4)

您需要“逃避”嵌入式引号。变化:

printf("\nInput word is "%c". contains %d input character. Index of %c in it is %d\n", word, charsInWord(word), c, indexOf(word, c));

为:

printf("\nInput word is \"%c\". contains %d input character. Index of %c in it is %d\n", word, charsInWord(word), c, indexOf(word, c));

或者只使用单引号。

答案 1 :(得分:1)

更改

"Input word is "%c". contains %d input character."

"Input word is \"%s\". contains %d input character."

引用的转义是删除错误。从%c%s的更改是因为您需要%s来打印字符串。

答案 2 :(得分:0)

您需要转义格式字符串中的引号。

printf("\nInput word is "%c". contains %d input character. Index of %c in it is %d\n", word, charsInWord(word), c, indexOf(word, c));

应该是

printf("\nInput word is \"%c\". contains %d input character. Index of %c in it is %d\n", word, charsInWord(word), c, indexOf(word, c));

答案 3 :(得分:0)

printf("\nInput word is "%c". contains %d input

对于初学者,你需要转义那些引号,如下所示:

printf("\nInput word is \"%c\". contains %d input

接下来,确保格式字符串后面的参数类型与格式说明符所期望的类型相匹配。也就是说,如果您指定%c,请确保相应的参数为char。如果指定%f,请确保相应的参数是浮点类型,依此类推。

在这种情况下,您可能尝试为第一个参数传递字符串(word),您已将其指定为字符(%c)。如果您要传递%schar[](并确保字符串为空终止),请使用char*格式说明符。

答案 4 :(得分:0)

使用现代GCC库,您可以消除%s超越缓冲区并扰乱程序的风险。出于相关原因,检查scanf()的返回值也是必不可少的。你也可以分解你的长队。该示例对函数中未定义的函数使用了一些标准库调用:

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

int main() 
{ 
    char *word = 0;
    char c;

    printf("Enter a word and a character separated by a blank ");
    /* %ms is in GCC and the upcoming POSIX.1 standard */
    if(2 != scanf("%ms %c", &word, &c)) {
        fputs("oops, something went wrong in that input.\n", stderr);
        return -1;
    } 
    char *first = strchr(word, c);  /* NULL if not found */
    printf("\nInput word is \"%s\". contains %u input character. "
           "Index of %c in it is %ld\n",
           word, (unsigned int)strlen(word), c,
           first - word);  /* probably negative if it wasn't found */

    free(word);
    return 0;
}

处理不完整的字母留作练习......: - )