C - While循环在使用getch()

时间:2016-04-12 10:47:01

标签: c loops while-loop infinite getch

我不确定此问题是否曾被提出过,但我找不到确切的问题,所以就在这里。

在程序开始时,我有一个登录屏幕,它将隐藏输入的密码。然后将它与txt文件中的用户名和密码进行比较。为了这个问题,我只需在主要文件中设置凭据。

点击输入以断开密码输入后,它退出do while,然后应该启动while并使用scanf从菜单中选择。 该程序忽略scanf并无限运行。这些函数在上面声明,我包含了stdio.h,conio.h,stdlib.h,string.h。 代码如下:

    void main() {

int i, run = 0, choice, loc = 0;
node* top;
top = NULL;

login();
//While the run loop is 0 show the menu and take choice input
do {

    printf("\n\tMenu\n");
    printf("\n1 - Add survey");
    printf("\n2 - Display all survey");
    printf("\n3 - Display a survey");
    printf("\n4 - update a survey");
    printf("\n5 - delete a survey");
    printf("\n6 - generate survey statistics");
    printf("\n7 - Print to file");
    printf("\n8 - Quit");
    printf("\nPlease enter your choice:");
    scanf("%d", &choice);


    if (choice == 1) {
        addSurvey(&top);
    }// add a survey
    else if (choice == 2) {
        displaySurveys(top);
    }//display all surveys
    else if (choice == 3) {
        printf("\nEnter the PPS: ");
        scanf("%d", &loc);
        diplaySurvey(top, loc);
    }//display particular survey
    else if (choice == 4) {
        printf("\nEnter the PPS: ");
        scanf("%d", &loc);
        updateSurvey(top, loc);
    }// update a survey
    else if (choice == 5) {
        printf("\nEnter the PPS: ");
        scanf("%d", &loc);
        deleteSurvey(&top, loc);
    }// delete a survey
    else if (choice == 6) {
        generateStats(&top);
    }// generate statistics
    else if (choice == 7) {
        printToFile(&top);
    }//Print to file
    else if (choice == 8) {
        run = 1;
        exit(0);
    }//Quit

} while (run == 0);//while running

} //主

void login(){

int i, allGood = 1;
char letter, username[10], password[10], user[10] = "user", pass[10] = "pass";

//the login screen
do { // Do this while its not all good :(
    printf("\nTo log in please enter your credentials: ");
    printf("\nUsername: ");
    scanf("%", username);
    printf("Password: ");

    //Take in a password from the user and replace the input with ****
    for (i = 0; i < 10; i++) {
        letter = getch();
        //if the user hits the return key end password input 
        if (letter == '\r') {
            password[i] = '\0';
            printf("\nPress ENTER to continue!\n");
            break;
        }//if
         //If the user enters backspace delete the last char
         /*else if (letter == '\p') {
         i--;
         password[i - 1] = '\0';
         }//else if*/
        password[i] = letter;
        printf("*");
    }//for

    if (!(strcmp(user, username) && strcmp(pass, password))) {
        allGood = 0;
    }//if the inputted credentials & the actual match set all good to 0
} while (allGood == 1);
fflush(stdin);
getch();

} //登录

0 个答案:

没有答案