I want to create a simple program in C that will display a menu, and the user must choose from the choices by choosing a char. This is the code I tried:
#include <stdio.h>
void menu();
int main(int argc, char **argv)
{
menu();
return 0;
}
void menu(){
char choix;
printf("(C)réer un fichier\n");
printf("(L)ire un fichier\n");
printf("(E)crire sur un fichier\n");
printf("(S)upprimer un fichier\n");
do{
choix = tolower(getchar());
printf(choix);
}while((choix != 'c') || (choix != 'l') || (choix != 'e') || (choix != 's'));
printf("end");
}
but when I run my application, I get this message in console:
./geany_run_script.sh: line 5: 6582 Segmentation fault (core dumped) "./main"
And this is a screenshot :
printf
's argument needs to be a string, but you're passing it a char
in
printf(choix);
It's treating that character as a pointer, but it's not going to be a valid pointer, and it's pointing somewhere very low in memory that you should not be trying to access. Instead, you should either pass printf
a string with a format directive that expects a char, such as in
printf("%c", choix);
or you could use a function like putchar
and do
putchar(choix);
However, once you get that worked out, you'll have some problems ending your loop. You end when
(choix != 'c') || (choix != 'l') || (choix != 'e') || (choix != 's')
but every character is not the same as at least one of c
, l
, e
, or s
. That is, suppose the user types x
. Then the first part (choix != 'c')
will be true and you'll quit. The same thing would happen if the user had typed e
, which is supposed to be one of your options. If you're trying to loop until the user puts in one of the designated characters, you need to loop while
(choix != 'c') && (choix != 'l') && (choix != 'e') || (choix != 's')
That is, you continue looping as long as it's not c
, and it's not l
_, and it's not e
, and it's not s
. You could also phrase this as "loop while it's not ( equal to c
or equal to
l` or …)", in which case you could loop while
!( choix == 'c' || choix == 'l' || choix == 'e' || choix == 's' )
This mistake actually appears somewhat frequently on Stack Overflow, but it's rather hard to search for. Here's an answered question in Ruby that addresses this issue: