Skip to content

Instantly share code, notes, and snippets.

@pileon
Created October 27, 2016 09:29
Show Gist options
  • Save pileon/87c6c9648f27d60b3cd13db34456ef81 to your computer and use it in GitHub Desktop.
Save pileon/87c6c9648f27d60b3cd13db34456ef81 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <limits.h>
// Important note: When reading input, something like 123abc is considered
// a valid value, and will be read as 123. The non-numeric input will not be
// detected immediately.
// This is because of how the scanf function works, and can't be solved with
// the current limitations (unless we read as a string and attempt to convert
// it to a number manually, either through strtol or with our own function
// (the atoi function can't be used, it's prone to the same problem)).
// Reads until newline (or end of file), discarding all it reads
void skip_line(void)
{
int c;
while ((c = getchar()) != '\n' && c != EOF)
{
}
}
// Get the expected number of values to read
int get_expected(void)
{
while (1)
{
printf("Please input the number of values to read: ");
fflush(stdout); // Make sure the output is flushed and written to the console
int expected;
int result = scanf("%d", &expected);
if (result == EOF)
{
return -1;
}
else if (result == 1 && expected >= 0)
{
// Got a valid number
return expected;
}
else
{
// Either not a valid input, or a negative value
skip_line(); // Skip everything until the end of the line (or end of input)
printf("Not a valid number, it must be a positive number.\n");
}
}
}
// Get a single value
int get_value(void)
{
while (1)
{
printf("Enter a value: ");
fflush(stdout); // Make sure the output is flushed and written to the console
int value;
int result = scanf("%d", &value);
if (result == EOF)
{
return INT_MIN; // Lets hope the user doesn't input the minimum integer value
}
else if (result == 1)
{
// Got a valid value
return value;
}
else
{
// Not a valid value
skip_line(); // Skip everything until the end of the line (or end of input)
printf("Not a valid value, please try again.\n");
}
}
}
int main(void)
{
int expected = get_expected();
if (expected <= 0)
{
printf("No expected values, exiting\n");
return 0;
}
double sum = 0;
int value = 0;
int counter;
for (counter = 0; counter < expected && value != INT_MIN; ++counter)
{
value = get_value();
if (value != INT_MIN)
{
sum += value;
}
}
double average = sum / counter;
if (value == INT_MIN)
{
printf("Premature end of values, average = %f\n", average);
}
else
{
printf("Average = %.02f\n", average);
}
return 0;
}
@pileon
Copy link
Author

pileon commented Oct 27, 2016

With severe limitations on the functions that can be called, shows a way to read numbers and calculate an average of that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment