问题描述:

#include <stdio.h>

/* print a given string and a number in a pre-determined format. */

void

print_string(int num, char* string)

{

printf("String '%d' - '%s'\n", num, string);

}

int

main(int argc, char* argv[])

{

int i;

/* check for command line arguments */

if (argc < 2) { /* 2 - 1 for program name (argv[0]) and one for a param. */

printf("Usage: %s [<string> ...]\n", argv[0]);

return(1);

}

/* loop over all strings, print them one by one */

for (argc--,argv++,i=1 ; argc > 0; argc--,argv++,i++) {

print_string(i, argv[0]); /* function call */

}

printf("Total number of strings: %d\n", i);

return 0;

}

This code is supposed to count the words of the sentence. For example, "how are you" output should be three, but when I run it in C++ the output is 4. Can you please tell me what is wrong with this code?

网友答案:
/* loop over all strings, print them one by one */
int i;
for(i=1; i < argc; i++)
    print_string(i, argv[i]);

/* EDIT:  Add this line to print the total number of strings */
printf("Total number of strings: %d\n", i-1);
网友答案:
for (argc--,argv++,i=0 ; argc > 0; argc--,argv++)
{
    print_string(++i, argv[0]);  /* function call */
}

This should also solve your problem. The issue was, you have initialize i by 1 and then increment it argc times.

相关阅读:
Top