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?
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;
}