Reputation: 43
I am working on a program that is supposed to keep asking the user for input, sort of like a menu until they choose the option to quit. Depending on what they choose, some sort of operation will be done depending on the choice. Right now I am just trying to test that the menu will keep being printed to the user, but it exits automatically once i run the program once. This is what I have:
#include <stdio.h>
#include <string.h>
int main()
{
char str;
unsigned int hex;
int decimal;
while(str != 'Q'){
printf("Choose an Option (C, M, Q, S, V): ");
scanf("%c", &str);
if(str == 'C'){
printf("C working.");
break;
}
else if(str == 'M'){
printf("M working.");
break;
}
else if(str == 'S'){
printf("S working.");
break;
}
else if (str == 'V'){
printf("V working.");
break;
}
}
return 0;
}
Q is the option that would quit the program immediately if selected, but the other ones are not.
An example output I have gotten:
Choose an Option (C, M, Q, S, V): M
M working. (base)
Upvotes: 0
Views: 1200
Reputation: 133
if you want the menu to keep printing to the user just remove the break statement in each of the (if,else if) blocks. because the break and continue statements affects the nearest repetition statement to them which is the while loop in your code.
Upvotes: 1
Reputation: 77
The break exits from the while loop. The if
statement is not a looping structure so the break
is for the nearest loop which is the while.
Upvotes: 2
Reputation: 186823
it seems you want to break
on 'Q'
only:
int main()
{
char str = null;
unsigned int hex;
int decimal;
while(1 == 1) { /* infinite loop until user breaks with a help of Q */
printf("Choose an Option (C, M, Q, S, V): ");
scanf("%c", &str);
if (str == 'Q') /* break on Q only */
break;
/* All the other cases: perform the operation and ask again */
if(str == 'C'){
printf("C working.");
}
else if(str == 'M'){
printf("M working.");
}
else if(str == 'S'){
printf("S working.");
}
else if (str == 'V'){
printf("V working.");
}
}
return 0;
}
Upvotes: 0
Reputation: 70244
You need to initialize str
.
int main()
{
char str = 0;
unsigned int hex = 0;
int decimal = 0;
...
Upvotes: 0