How to convert int type to char and use it to stop the loop?

advertisements

I am new in C programming. I wrote a programme with "for" loop which will take two int type inputs K and M and print out the calculation (of hash function in division method). And if I enter q or Q as the input of K or M then it will exit. How will i do that? anyone help me.

int main(){

int K;
int M;

for(;;)
{
    printf("Enter the value of K: \n");
    scanf("%d",&K);

    printf("Enter the value of M: \n");
    scanf("%d",&M);

    printf("The Hash address of %d and %d is %d",K,M,K%M);
}
return system("pause");}


This checks the return of scanf() to see if the scan was successful. If not, the buffer is cleared and checked for a 'q' that indicates that the program should exit.
getint() accepts a prompt message and a pointer to a flag. Setting the flag to -1 tells the caller to exit.

#include <stdio.h>
#include <math.h>

int getint ( char *prompt, int *result);

int main ( int argc, char* argv[])
{
    int K, M;
    int ok = 0;

    do {
        K = getint ( "\nEnter the value of K ( or q to quit)\n", &ok);
        if ( ok == -1) {
            break;
        }
        M = getint ( "\nEnter the value of M ( or q to quit)\n", &ok);
        if ( ok == -1) {
            break;
        }
        printf("\nThe Hash address of %d and %d is %d\n", K, M, K % M);
    } while ( ok != -1);

    return 0;
}

//the function can return only one value.
//int *result allows setting a flag:
//  0 the function is looping
//  1 the function is returning a valid int
// -1 the function returns and the program should exit
// the caller can see the flag of 1 or -1
int getint ( char *prompt, int *result)
{
    int i = 0;
    int n = 0;

    *result = 0;

    do {
        printf("%s", prompt);
        if ( scanf("%d",&n) != 1) {// scan one int
            while ( ( i = getchar ( )) != '\n' && i != 'q') {
                //clear buffer on scanf failure
                //stop on newline
                //quit if a q is found
            }
            if ( i != 'q') {
                printf ( "problem with input, try again\n");
            }
            else {//found q. return and exit
                *result = -1;
                n = 0;
            }
        }
        else {//scanf success
            *result = 1;//return a valid int
        }
    } while ( *result == 0);

    return n;
}