-
Re: Question
The question that was given to me is to prompt the user to enter a number followed by an operator and lastly a number,
eg:
User Input: 5 + 5
Program Output: 5 + 5 is 10
I tried using the statements below
scanf("%lf",&number1); //number
scanf("%s",&operate); //operator
scanf("%lf",&number2); //number
and it works when I types 5 + 5, it fails when I entered 5+5 or
5+ 5 or even 5 +5. How do I recitify this problem?
Thanks for your help in advance.
-
this depends on how you enter numbers(and operators), do you want to enter numbers one by one, or the whole string?
-
i believe a string is more preferable
-
then what you do is read a line to the temporary buffer using fgets, and then you use sscanf to get those values from the string.
-
scanf (and friends) is designed to work with strict formatting. You can get around this with ugly hacks, but for the most part it's better to read an entire line with fgets and then parse it at your leisure. In this case, strtol gives you just what you need (it's less concise though :():
Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
long int a, b;
char op;
char buffer[BUFSIZ];
char *end;
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
/* Split up the input */
a = strtol ( buffer, &end, 0 );
if ( end == buffer )
return EXIT_FAILURE;
while ( *end != '\0' && isspace ( *end ) )
++end;
op = *end++;
b = strtol ( end, &end, 0 );
if ( end == buffer )
return EXIT_FAILURE;
/* Perform the operation */
if ( op == '+' )
printf ( "%ld\n", a + b );
}
return EXIT_SUCCESS;
}
-
thanx prelude and viaxd but here a question to prelude, i tried your code above, it worked and when i switch the variables to double and %f respectively it fails. did i do something wrong?
-
that's because the strtol function is only for use with integer variables. for floats you can use strtold(it has 2 arguments, not 3 as in strtol)
-
I check on that function and decided to change strtol to strtod. The funny thing is that i try to run values in it and the program gives me wrong answers
eg: 3.3 +6.6 and it gives me 6.6 instead of 9.9
-
>eg: 3.3 +6.6 and it gives me 6.6 instead of 9.9
That was my fault, sorry. I typed buffer when I meant to type end in the second call to strtol. ;) This works:
Code:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
int main ( void )
{
double a, b;
char op;
char buffer[BUFSIZ];
char *end;
if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
/* Split up the input */
a = strtod ( buffer, &end );
if ( end == buffer )
return EXIT_FAILURE;
while ( *end != '\0' && isspace ( *end ) )
++end;
op = *end++;
b = strtod ( end, &end );
if ( end == buffer )
return EXIT_FAILURE;
/* Perform the operation */
if ( op == '+' )
printf ( "%f\n", a + b );
}
return EXIT_SUCCESS;
}
Kind of scary, isn't it? ;)
-