如何将int转换为char类型并使用它来停止循环?

时间:2015-09-07 20:22:21

标签: c

我是C编程的新手。我用“for”循环编写了一个程序,它将采用两个int类型输入K和M并打印出计算(分割方法中的散列函数)。如果我输入q或Q作为K或M的输入,那么它将退出。我该怎么做?有人帮帮我。

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");}

2 个答案:

答案 0 :(得分:1)

true

答案 1 :(得分:1)

这将检查scanf()的返回以查看扫描是否成功。如果没有,则清除缓冲区并检查“q”,表示程序应该退出 getint()接受提示消息和指向标志的指针。将标志设置为-1会告诉调用者退出。

#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;
}