Hi there, I'm fairly new to C and after doing some research I know that a lot of people said to avoid scanf and should just use gets or something.. but.. I'm going to use it for now :)
The problem is..
Here is the code
Code:
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#define FLUSH_STDIN while ( getchar() != '\n' )
int main(void){
/* Clear stdout buffer */
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
char s[80]; // Input String
char width_c, height_c; // For storing the input
int width, height; // For storing the input AFTER converted into int
int area; // Area
/* Prompt for width */
printf("Please enter width: ");
gets(s);
sscanf(s, "%s", &width_c);
/* Check if input is digit, if not... */
while(!(isdigit(width_c))){
printf("Input Error: Invalid format\n");
printf("Please enter width: ");
gets(s);
sscanf(s, "%s", &width_c);
}
/* Prompt for height */
printf("Please enter height: ");
gets(s);
sscanf(s, "%s", &height_c);
/* Check if input is digit, if not... */
while(!(isdigit(height_c))){
printf("Input Error: Invalid format\n");
printf("Please enter height: ");
gets(s);
sscanf(s, "%s", &height_c);
}
/* Convert string value into int */
width = atoi(&width_c);
height = atoi(&height_c);
/* Display width and height */
puts("------------------------");
printf("Width is: %d\n", width);
printf("Height is: %d\n", height);
/* Calculate + print the area */
area = width * height;
puts("------------------------");
printf("Area is: %d\n", area);
return 0;
}
What I'm getting is :
Code:
Please enter width: 3
Please enter height: 4
------------------------
Width is: 0
Height is: 4
------------------------
Area is: 0
There was something else that I tried.. and the result was:
Code:
Please enter width: 3
Please enter height: 4
------------------------
Width is: 3
Height is: 43
------------------------
Area is: 129
as if the stdin buffer wasn't properly cleared.
Any tips on how I should do this? Thanks :)
P.S I'm using Eclipse CDT as IDE