c - 在 C 中打印数组时出错

标签 c arrays printf

错误发生在行:

printf("\n%s was found at word number(s): %d\n", search_for, pos);

我想打印我的整数数组 (pos),但我不知道该怎么做。我通过命令行运行它,但出现此错误:

search_word.c:57:28: warning: format specifies type 'int' but the argument hastype 'int *' [-Wformat] search_for, pos);

代码:

const int MAX_STRING_LEN = 100;

void Usage(char prog_name[]);

int main(int argc, char* argv[]) {
    char search_for[MAX_STRING_LEN];
    char current_word[MAX_STRING_LEN];
    int  scanf_rv;
    int loc = 0;
    int pos[MAX_STRING_LEN] = {0};
    int word_count = 0;
    int freq = 0;

    /* Check that the user-specified word is on the command line */
    if (argc != 2) Usage(argv[0]);
    strcpy(search_for, argv[1]);

    printf("Enter the text to be searched\n");
    scanf_rv = scanf("%s", current_word);
    while ( scanf_rv != EOF && strcmp(current_word, search_for) != MAX_STRING_LEN )  {
        if (strcmp(current_word, search_for) == 0) {
            loc++;
            freq++;
            pos[loc] = word_count;
        }
        word_count++;
        scanf_rv = scanf("%s", current_word);
    }
    if (freq == 0)
        printf("\n%s was not found in the %d words of input\n",
               search_for, word_count);
    else
        printf("\n%s was found at word number(s): %d\n",
               search_for, pos);
    printf("The frequency of the word was: %d\n", freq);

    return 0;
}  /* main */

/* If user-specified word isn't on the command line,
 * print a message and quit
 */
void Usage(char prog_name[]) {
    fprintf(stderr, "usage: %s <string to search for>\n",
            prog_name);
    exit(0);
}  /* Usage */

最佳答案

pos 是一个数组。你必须循环打印它。

else {
    printf("\n%s was found at word number(s): ",
           search_for);
    for (int index = 0; index < MAX_STRING_LEN; index++)
          printf("%d ", pos[index]);

    printf("\n");
 }

关于c - 在 C 中打印数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25816766/

相关文章:

c# - LINQ to Entities 无法识别方法 'Newtonsoft.Json.Linq.JToken get_Item(System.String)' 方法,

时间:2019-03-08 标签:c++coutvsprintf()

c++ - fprintf 的成本

c++ - 我试图将 vsnwprintf 包装在另一个结果奇怪的函数中,它似乎给出了它的地址而不是实际值

c - 使用用户空间的 Linux 加密 API 进行 RSA

C 皮质-M4 : How to access uint8_t data sent by UART (vcom) as int32_t

java - 如何将类中的属性与字符串进行比较?

php - 为什么我不能在 MongoDB 文档中存储关联数组?

c - 如何在RAM上定义const变量?

c++ - 这个类型转换意味着什么?