Reputation: 39
The error occurs in the line:
printf("\n%s was found at word number(s): %d\n", search_for, pos);
I want to print my array of ints (pos
) but I am not sure how to do so. I am running it through the command line and I am getting this error:
search_word.c:57:28: warning: format specifies type 'int' but the argument hastype 'int *' [-Wformat] search_for, pos);
Code:
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 */
Upvotes: 1
Views: 81
Reputation: 36458
You'd need to loop over the array. C doesn't have any way to print an array of int
s in a single statement:
else {
int i;
printf("\n%s was found at word number(s): ", search_for);
for ( i = 0; i < loc; ++i ) {
if (i > 0)
printf(", ");
printf("%d", pos[i]);
}
printf("\n");
}
Before that, though, make sure you increment loc
at the right time. As-is, you're leaving the first element empty.
if (strcmp(current_word, search_for) == 0) {
pos[loc] = word_count;
loc++;
freq++;
}
Upvotes: 1
Reputation: 775
pos
is an array. You have to print it in a loop.
Do
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");
}
Upvotes: 1