473,513 Members | 2,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

having problems with interactive error catching function

ok the function is supposed to accept only non-negative integers... but it still accepts letters input through the function. Such as '23e' still passes through. I tried to use isalpha in the or statement to cause an error, but it causes an error for everything input. How do I make an error occur when anything other than numbers are put in?

#include <stdio.h>
#define MAXLINE 20
int main(void)
{
char line[MAXLINE];
int error,n;
do{
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
error=sscanf(line, "%d",&n) !=1||n<=0;
if (error)
printf("\nERROR: Do it again.\n");
} while(error);
}

Nov 14 '05 #1
4 2151
On Thu, 1 Jan 2004 12:36:19 -0600, "interpim" <le***@atrc.navy.mil>
wrote:
ok the function is supposed to accept only non-negative integers... but it still accepts letters input through the function. Such as '23e' still passes through. I tried to use isalpha in the or statement to cause an error, but it causes an error for everything input. How do I make an error occur when anything other than numbers are put in?
Use strtol instead of sscanf and check the "updated" pointer to make
sure it points to the end of your string and not to an intermediate
non-integer.

#include <stdio.h>
#define MAXLINE 20
int main(void)
{
char line[MAXLINE];
int error,n;
do{
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
error=sscanf(line, "%d",&n) !=1||n<=0;
if (error)
printf("\nERROR: Do it again.\n");
} while(error);
}


<<Remove the del for email>>
Nov 14 '05 #2
interpim wrote:

ok the function is supposed to accept only non-negative integers...
but it still accepts letters input through the function. Such as
'23e' still passes through. I tried to use isalpha in the or
statement to cause an error, but it causes an error for everything
input. How do I make an error occur when anything other than
numbers are put in?

#include <stdio.h>
#define MAXLINE 20
int main(void)
{
char line[MAXLINE];
int error,n;
do{
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
error=sscanf(line, "%d",&n) !=1||n<=0;
if (error)
printf("\nERROR: Do it again.\n");
} while(error);
}


Please fix your line length. It should never exceed 80, and 65 is
about optimum.

Look up the %n specifier, which will show where the conversion
stopped. You can then examine the remainder of the input string,
to see if it consists of anything other than white space, and
object if desired. From N869:

n No input is consumed. The corresponding argument
shall be a pointer to signed integer into which is
to be written the number of characters read from the
input stream so far by this call to the fscanf
function. Execution of a %n directive does not
increment the assignment count returned at the
completion of execution of the fscanf function. No
argument is converted, but one is consumed. If the
conversion specification includes an assignment-
suppressing character or a field width, the behavior
is undefined.

An alternative is to use strtol(), which can also return a pointer
past the converted value, and is probably clearer. I am not sure
whether or not strtoul() will object to a leading - sign, or
simply do the unsigned modulo operations. At any rate using
either also allows you to put firm limitations on the input range.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #3


interpim wrote:
ok the function is supposed to accept only non-negative integers... but it still accepts letters input through the function. Such as '23e' still passes through. I tried to use isalpha in the or statement to cause an error, but it causes an error for everything input. How do I make an error occur when anything other than numbers are put in?

#include <stdio.h>
#define MAXLINE 20
int main(void)
{
char line[MAXLINE];
int error,n;
do{
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
error=sscanf(line, "%d",&n) !=1||n<=0;
if (error)
printf("\nERROR: Do it again.\n");
} while(error);
}


Study up on the Standard C function strtoul. It is very
useful in validating a positive integer.

An example:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>

typedef enum {NO, YES} bool;

char *fgetline(FILE *fp);
char *getline(void);
bool StrtoUnsigned(const char *num, unsigned *ud);

int main(void)
{
char *s;
unsigned ud;

while(1)
{
printf("Input a positive integer: ");
fflush(stdout);
s = getline();
if(!s || StrtoUnsigned(s, &ud)) break;
free(s);
printf("\nERROR: Do it again.\n");
}
if(s)
{
printf("The number is %u\n",ud);
free(s);
}
return 0;
}

bool StrtoUnsigned(const char *num, unsigned *ud)
{
unsigned long ul;
char *s;

errno=0;
ul = strtoul(num,&s,10);
if(*num != '-' && *s == '\0' && errno != ERANGE &&
ul <= UINT_MAX)
{
*ud = ul;
return YES;
}
return NO;
}

char *fgetline(FILE *fp)
{
char *tmp,buf[63],*s,*s1;
size_t count, size = 63;

for(count = 1,tmp=s=NULL; (fgets(buf,sizeof buf,fp)!=NULL); )
{
if((tmp = realloc(s,count++*(size+1)))==NULL) break;
if(s == NULL) *tmp='\0';
s=tmp;
strcat(s,buf);
if((s1 = strrchr(s,'\n'))!=NULL)
{
*s1='\0';
break;
}
}
if(tmp) /* resize the allocated space to string length */
if((tmp= realloc(s,strlen(s)+1))!=NULL)
s = tmp;
if(!tmp)
{ /* Oops! stream read error or allocation failure */
free(s);
s=NULL;
}
return s;
}

char *getline(void)
{
return fgetline(stdin);
}

--
Al Bowers
Tampa, Fl USA
mailto: xa******@myrapidsys.com (remove the x to send email)
http://www.geocities.com/abowers822/

Nov 14 '05 #4
in comp.lang.c i read:
char line[MAXLINE];
int error,n;
do{
printf("Input a positive integer: ");
fgets(line, MAXLINE, stdin);
error=sscanf(line, "%d",&n) !=1||n<=0;


in addition to the other comments i'll add that if fgets reaches eof or
encounters an error line will not have been modified, and if this happens
on the first iteration the content would (continue to) be indeterminate so
calling sscanf would have undefined behavior. the solution is to check the
return value from fgets, e.g.,

if (0 == fgets(line, sizeof line, stdin)) break;

if you do this you must ensure that code following your loop doesn't depend
on line, error or n having a value, e.g.,

} while(error);
if (ferror(stdin)) fputs("error reading stdin\n", stderr), abort();
if (feof(stdin)) fputs("unexpected eof reading stdin\n", stderr), abort();

--
a signature
Nov 14 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
1961
by: George Nachman | last post by:
I'm interested in implementing a command-line PHP app that takes input line-by-line (for example, using Readline) and executes commands as they are entered. It would need to know the difference...
20
2185
by: Lucas Raab | last post by:
I'm done porting the C code, but now when running the script I continually run into problems with lists. I tried appending and extending the lists, but with no avail. Any help is much appreciated...
2
4060
by: Chris | last post by:
I'm desperately trying to get my site finished against the clock. It looks great in FF, Opera and IE6 but falls apart in IE5 and Safari. I HAVE to have it ok for IE5.x. Has anyone got any...
13
2908
by: python | last post by:
hello and thanks for reading this, i have been a dos/windows user using some form of the basic language for 30 years now. i own and run a small programming company and there is one feature that...
5
2139
by: Chua Wen Ching | last post by:
Hi, I read from this tutorial at codeproject Question A: http://www.codeproject.com/csharp/GsXPathTutorial.asp regarding xpath.. but i try to apply in my situation, and can't get it...
4
7600
by: James Radke | last post by:
Hello, I am looking for guidance on best practices to incorporate effective and complete error handling in an application written in VB.NET. If I have the following function in a class module...
3
7826
by: Shawnk | last post by:
I use two classes to manage the Main() command line (and alot of other stuff) for my prototyping environment. I tryed putting the MainClass in a DLL and just having the other class (which gets...
14
1467
by: John Salerno | last post by:
Here's an exercise I was doing to guess a number from 1-100. Just for fun (ha ha) I decided to add some error checking too, and now when I run it, the DOS prompt flashes real quick and disappears....
9
2093
by: 47computers | last post by:
Pretty new to PHP, I recently started learning about error trapping. As of right now, I include the following into a page in my website: -------BEGIN PASTE-------- error_reporting(E_ERROR |...
0
7259
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7158
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7380
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7535
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7098
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
5085
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
3232
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
3221
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
455
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.