So I am currently writing a program in C that using a switch statement can allow a string to be entered then depending on the value you choose from the menu determine what to do with it.
Here is my code,
#include <stdio.h>
int main()
{
int menu, end, i;
char string[100];
end = 0;
do
{
printf("Welcome to the string operations program.\n\n");
printf("1 - Enter a string\n");
printf("2 - Display the message using the string\n");
printf("3 - Count the number of characters in the string\n");
printf("4 - Display the string backwards\n");
printf("5 - Exit\n\n");
printf("Option: ");
scanf("%d", &menu);
switch (menu)
{
case 1:
printf("String: ");
scanf("%s", string);
break;
case 2:
printf("This is a message: Hello %s\n", string);
break;
case 3:
printf("There are %d characters in %s\n", strlen(string), string);
break;
case 4:
printf("string reversed gives: ");
for (i = strlen(string) - 1; i >= 0; i--)
printf("%c", string[i]);
printf("\n");
break;
case 5:
printf("Exit");
return 1;
break;
default:
printf("Invalid input, try again.\n");
break;
}
}while (end != 1);
return 0;
}
It seems to work for everything when I run it through 1,2,3,4,5 as that is the requirement for the question. However when i enter a letter for example 't' it goes to the default section as expected. When it enters this it goes into an infinite loop.
Can anyone help me and show me how to not make this an infinite loop but just have it return to the start as the user input was not allowed?