0

我是 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;
}
4

5 回答 5

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));

或者只使用单引号。

于 2013-05-17T03:07:55.217 回答
1

改变

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

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

引号的转义是为了消除错误。从%cto的变化%s是因为你需要%s打印出字符串。

于 2013-05-17T03:10:29.177 回答
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;
}

处理未找到的信件留作练习...... :-)

于 2013-05-17T08:01:03.967 回答
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));
于 2013-05-17T03:08:03.023 回答
0
printf("\nInput word is "%c". contains %d input

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

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

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

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

于 2013-05-17T03:09:34.613 回答