Originally Posted by
rodrigorules
can u give me an example of what i would put in mine with sscanf and fget?
Code:
#include <stdio.h>
#include <string.h> /* for the call to strchr() */
#include <stdlib.h> /* for the call to exit() */
int main(void)
{
enum {
BUF_MAX = 15
};
int num1;
int num2;
char yorn;
char buffer[BUF_MAX] = { 0 };
char *p;
printf("Enter a basic number <ENTER>: ");
fflush(stdout);
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
perror("fgets()");
exit(EXIT_FAILURE);
}
if ((p = strchr(buffer, '\n')) != NULL) {
*p = '\0';
}
if ((sscanf(buffer, "%d", &num1)) != 1) {
puts("Error: call to sscanf() failed");
exit(EXIT_FAILURE);
}
printf("Now enter another number <ENTER>: ");
fflush(stdout);
/* Get the user input into the array 'buffer' with
* fgets() - if fgets() returns NULL, then there was
* some sort of trouble, and we deal with it accordingly
*/
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
perror("fgets()");
exit(EXIT_FAILURE);
}
/* if there is a newline stored at the end of the buffer
* it most likely would be advantageous to eliminated it.
* Search for a newline with strchr(), and if we find it,
* replace it with a null terminator.
*/
if ((p = strchr(buffer, '\n')) != NULL) {
*p = '\0';
}
/* sscanf() (and the other variants of scanf()) return a value
* which corresponds to the number of conversions made. We will
* check and see that, in this case, we get 1 (one) conversion
* corresponding to the one int we are looking to get. If we don't
* get 1 (one), then there is a problem, and we deal with it as needed.
*/
if ((sscanf(buffer, "%d", &num2)) != 1) {
puts("Error: call to sscanf() failed");
exit(EXIT_FAILURE);
}
printf("You entered %d and %d\n", num1, num2);
printf("-------\n");
printf("Would you like to multiply the two values? Y/N <ENTER>: ");
fflush(stdout);
yorn = getchar();
if (yorn == 'y' || yorn == 'Y') {
printf("Your numbers multiplied are %d\n\n", num1 * num2);
} else {
printf("Ok then, thanks for using my basic program!");
}
return 0;
}
Voila - don't say you never had anything done for you. Of course doing code like that could get big in a real hurry, so you might want to write your own 'getnum' function which gets an integer from the user, and returns it to be used as you wish.
~/