Here's my solution, similar to what Fe2O3 did:
#include <stdio.h> // IO
#include <stdbool.h> // Boolean values
int main(void)
{
int value; // Integer value
char ch; // Character value
bool ended = false; // Loop ended state
const unsigned int END_CH_LEN = 2; // Length of ending characters array
char stop_ch[END_CH_LEN] = {'q', 'Q'}; // Ending characters
for (int i = 0; i < 100; i++)
{
// Check loop ended state
if (ended)
{
break;
}
// Print prompt
printf("Enter a number or quitting character (q / Q): ");
// Try to read integer, and check if the value is integer
if (scanf("%d", &value) != 1)
{
// Read character
scanf("%c", &ch);
// Check for ending characters
for (unsigned int i = 0; i < END_CH_LEN; i++)
{
// If match detected
if (ch == stop_ch[i])
{
// Exit loop
ended = true;
break;
}
}
}
else
{
// Print integer
printf("Integer value: %d\n", value);
}
}
return 0;
}
But still, as Fe2O3 previously mentioned, this code is not very scalable; the expected integer is fixed in size, and depending on the return value of scanf
to detect non-numerical inputs may break things in the future. If possible, read everything into a string first, then use something like strtol
for integer conversion, coupled with dynamic memory allocation for variable-sized strings if needed.