I input age as 30 but its not printing my if statement. Can i know why ? Thanks
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#define BUFFSIZE 512
int main()
{
int a;
char *buffer[BUFFSIZE];
write(1,"Please Enter your age: ",23);
a=read(0,*buffer,100);
if(a>21)
write(1,"You are an adult",16);
return 0;
}
CodePudding user response:
This
char *buffer[BUFFSIZE];
declares an array of uninitialized pointers.
This
a=read(0,*buffer,100);
passes the first uninitialized pointer to read
, so almost certain returns an error (probably EFAULT).
If you were to fix that (remove the *
from both lines), it would still return 3 if you enter 30Enter on the keyboard (3 characters entered)
Fixing all that, you end up with something like:
int main() {
int len;
char buffer[BUFSIZE];
write(1,"Please Enter your age: ",23);
len=read(0,buffer,BUFSIZE-1);
if (len <= 0) {
write(1, "invalid input", 13);
} else {
buffer[len] = '\0';
char *end;
int age = strtol(buffer, &end, 0);
if (*end != '\n')
write(1, "input not a (just) a number", 27);
if(age > 21)
write(1,"You are an adult",16);
}
return 0;
}
There's more stuff you can do with error checking (for example, you might want to ignore spaces on the end of the line, or other questionable input), but this shows where to start.
CodePudding user response:
If you consult the documentation for read
you will see that the return value is the number of bytes read. You will need to read the characters in buffer
and convert them from a string to an int
instead of doing what you are doing.
The C standard library provides functions like atoi
and scanf
that you can use to convert the string into a number, but it's pretty easy to do it yourself and it's a good exercise for a new C programmer.
CodePudding user response:
Try this out, which changes read for more commonly used fscanf:
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
write(1,"Please Enter your age: ",23);
fscanf(stdin, "%d",&a);
if(a>21)
write(1,"You are an adult",16);
return 0;
}