Another "integer only" problem
Hi and Happy New Years to all.
This is yet another question about writing a program that accepts only integers as valid input. The basics are the same as other posters: read in the users input, if it is not an integer, loop a request for input until it is an integer.
I think I have the logic figured out on how to do it (thanks Hammer for the informative FAQ), but I am stuck on a problem getting the entire user input evaluated.
Currently my program only detects an invalid input when the input is in the format of ##X, where # is a digit, and X is alpha.
If e45 is entered, it likes it. If 4e5 is entered, that it likes too.
It will only fail if 45e is entered, or anytime the last character is not a digit, but only the last character.
I would like to figure out what is stopping it from reading the rest of the input.
The section of code that I really feel is to blame is the following:
[CODE]
length = strlen(line);
for (i = 0; i < length; ++i)
{
if (line[i] == '\n')
{
}
else
{
error = 0;
if ( isdigit (line[i] ))
[END CODE]
However, I don't have enough experience to troubleshoot this witout some guidance. I can tell what I think is happening- it is reading the last character input by the user, and if it is a digit, it is happy and doesn't look any further. Why it is not looking any further and evaluating the rest of the input is my concern.
Here is the entire code, I hope someone can enlighten me.
[CODE]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXLINE 100
int main(void)
{
char line[MAXLINE];
int n;
int i;
int length;
int error = 0;
do {
printf(" Enter a positive integer: \n");
printf("\n");
fgets(line, MAXLINE, stdin);
sscanf(line, "%d", &n);
length = 0;
length = strlen(line);
for (i = 0; i < length; ++i)
{
if (line[i] == '\n')
{
}
else
{
error = 0;
if(isdigit(line[i]))
{
}
else
{
error = 1;
}
}
}
if (error)
{
printf("\n Try again!");
}
else
{
printf("\n Looks like an integer to me. Thanks!\n");
}
} while (error);
return 0;
}
[END CODE]
RedZippo