#include <stdio.h>
#include <string.h>
int main(){
char *command="0";
do {
printf("[A]dd, [P]rint, [Q]uit\n");
scanf("%s", command);
while (strcmp(command, "a") != 0 && strcmp(command, "A") != 0 && strcmp(command, "p") != 0 && strcmp(command, "P") != 0){
printf("Invalid input. Please enter one of the commands listed above.\n");
scanf("%s", command);
}
if (strcmp(command, "a") == 0 || strcmp(command, "A") == 0){
printf("You selected add.\n");
}
else if (strcmp(command, "p") == 0 || strcmp(command, "P") == 0){
printf("You selected print.\n");
}
}while (strcmp(command, "q") != 0 && strcmp(command, "Q")!= 0);
return 0;
}
I want the program to take in a letter from the user from one of the specified commands printed in the beginning. I want the program to exit if they enter q or Q. Took me a while simply to figure out how to do comparisons with strings for the loops and ifs. now when i run the program it crashes though. Looking for insight as to why its crashing.
command: it points to a string literal. Try an array instead:char command[] = "0";. and be sure to limit the length of the string read with the scanf:scanf("%1s")scanfis trying to write N bytes to the address pointed bycommand, which is a string-literal (read-only). You need to allocate enough memory to store these N bytes, or declare a fixed-length array ofchars. Example:char command[255]; scanf("%254s", command);