#include <stdio.h>
#include <stdlib.h>
// Function prototypes
void askFavoriteColor();
void clearInputBuffer();
int main()
{
int choice;
do
{
// Display the menu
printf("\nWhat would you like to do?\n");
printf("4. Exit.\n");
printf("Please enter your choice: ");
// Handle non-numeric input
// NOLINTNEXTLINE
if (scanf("%d", &choice) != 1)
{
printf("Invalid input. Please enter a valid number.\n");
clearInputBuffer(); // Clear the input buffer
continue; // Skip to the next loop iteration
}
getchar(); // Consume the newline left by scanf
// Handle user choice with switch
switch (choice)
{
case 1:
askFavoriteColor();
break;
case 4:
printf("Exiting... Goodbye!\n");
break;
default:
printf("Invalid choice. Please try again.\n");
break;
}
} while (choice != 4);
return 0;
}
void askFavoriteColor()
{
char *color = NULL;
size_t size = 0;
int ch;
printf("What is your favorite color? ");
// Dynamically allocate memory and read input character by character
while ((ch = getchar()) != '\n' && ch != EOF)
{
color = realloc(color, size + 1); // Reallocate memory for each new character
if (!color)
{
printf("Memory allocation failed.\n");
return;
}
color[size++] = ch; // Add the character to the string
}
// Null-terminate the string
color = realloc(color, size + 1);
if (color)
{
color[size] = '\0'; // Null-terminate the string
printf("Oh, %s is a beautiful color!\n", color);
}
free(color); // Free dynamically allocated memory
}
// Function to clear the input buffer
void clearInputBuffer()
{
int c;
while ((c = getchar()) != '\n' && c != EOF)
{
// Just loop to clear the buffer
}
}