Question

I'm writing a C program that optionally accepts character inputs from the command line. If the user inputs characters at the command line, the program should print the ascii value of those characters. I'm running into problems with 1) writing the printf statement and 2) skipping printing the inputs if the user doesn't send anything from the command line. Here is what I've written:

int main(int argc, char *argv){
    char thisChar; //Holds the character value of the current character.
    int ascii; //Holds the ascii value of the current character.
    int x = 1; //Boolean value to test if user input 0, our while loop break condition.
    int i = 0; //Counter for the following for loop

     if(argc > 0){
        for(i; i<argc; i++){
            thisChar = argv[i];
            printf("%c\nAscii: %d\n", thisChar, thisChar);//prints the character value of thisChar followed by its ascii value.
        }
        printf("Done.");
    }
}

When I call it from the command line like this:

./ascii F G h

The output is:

� 
k 
� 
� 
Done.

Is the problem in my printf statement? And why does the if condition evaluate to true even if I send no input?

Was it helpful?

Solution

The prototype is

int main(int argc,char *argv[]) // argv is an array of char pointers (= string)

If you want to print the first character of the string, you should try something like this :

int main(int argc,char *argv[]) {
  int i;
  char thisChar;
  for (i = 1; i < argc; i++) { // argv[0] may be the file name (no guarantee, see Peter M's comment)
    thisChar = argv[i][0]; // If the parameter is "abc", thisChar = 'a'
    printf("%c\tAscii: %d\n", thisChar, thisChar);
  }
  return 0;
} 

OTHER TIPS

The correct prototype of main is main(int argc, char *argv[]), not main(int argc, char *argv) (char **argv also works). The second parameter is an array of char pointers, each one pointing to a string representing one of the tokens on the command line.

You'll need to loop over each element of argv and, for each one, loop over the characters (terminated by a null byte), printing each one.

Also, argc is always at least 1 as argv[0] is the program name.

int main(int argc, char *argv[])

argv parameter is the array of character string of each command line argument passed to executable on execution.

int main(int argc, char *argv[]){
   char thisChar; //Holds the character value of the current character.
   int i = 0; //Counter for the following for loop

   if(argc > 0){
      for(i; i<argc-1; i++){
         thisChar = *argv[i + 1];
         printf("%c\nAscii: %d\n", thisChar, thisChar);
      }
      printf("Done.");
   }
return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top