【发布时间】:2014-01-09 19:48:06
【问题描述】:
在我的 C 程序中,我尝试使用 scanf 从控制台获取字符串 (char*) 输入,但是,无论输入什么,输入总是变成值 1638238:
#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);
}
}
}
例子:
输入:-e
输出:无法识别的命令“1638238”
编译器:Tiny C
编辑:我可以输入任何东西,它会输出
请输入要解密的文件路径`
#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);
}
}
}
【问题讨论】:
-
使用
strcmp比较字符串。和char command[3]
标签: c pointers if-statement scanf