Reputation: 1089
In my C program, I am trying to use scanf
to get the string (char*
) input from the console, however, the input always then turns into the value 1638238
, whatever is inputted:
#include <stdio.h>
int main(void){
for(;;){
printf("Choose your option:\n-d for decryption\n-e for encryption\n");
char command[2];
char* input = command;
scanf("%s", input);
if(command == "-d"){
printf("Please enter the path of the file\n");
// decrypt
}
else if(command == "-e"){
printf("Please enter the path of the file\n");
// encrypt
}
else{
printf("Unrecognized command '%d'\n", command);
}
}
}
Example:
input: -e
output: Unrecognized command '1638238'
Compiler: Tiny C
Edit: I can input anything, and it outputs
Please enter the path of the file to decrypted`
#include <stdio.h>
#include <string.h>
int main(void){
for(;;){
printf("Choose your option:\n-d for decryption\n-e for encryption\n");
char command[3];
char* input = command;
scanf("%s", input);
if(strcmp(input, "-d")){
printf("Please enter the path of the file to be decrypted\n");
}
else if(strcmp(input, "-e")){
printf("Please enter the path of the file to be encrypted\n");
}
else{
printf("Unrecognized command '%d'\n", input);
}
}
}
Upvotes: 1
Views: 144
Reputation: 134346
if(command == "-d")
. Not at all.
command
refers to the base address of the array. What you want is to compare the content of those arrays, not their address
location.
you might want to use strcmp()
. Check here
word of caution: to use a char
array as string, you need to have a terminating \0
[NULL
] character. use char command[3];
instead.
EDIT:
To address the issue in the updated code, (copied into the answer from the comments below)
strcmp()
returns 0
in case of match. So, to determine the "matching condition", you need to use if (!strcmp(str1,str2))
form (note the !
).
To avoid the possibility of buffer overflow by lengthier input, limit the input to scanf()
by using
scanf("%2s", input); //when input is a 3 element char array
I hope you do realize that your for(;;)
loop is an absolute infinite loop, as you don't have any break
ing statement. Try to add one, based on your convenient logic.
Upvotes: 3
Reputation: 106042
To compare strings use strcmp
. command == "-e"
is a wrong way to compare. command
decays to a pointer to the first element of your input. By doing command == "-e"
, you are comparing a pointer with a string.
Upvotes: 0