简体   繁体   中英

How to exit while loop when enter key pressed in c code?

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

int main(void){

    char str[100];
    char final;
    int sum = 0;
    int i = 0;
    int reminder;

    printf("Enter an abitrarily long string, ending with carriage return > ");

    while(1){
        //get user input of string unless they enter key exit
        if((scanf("%[^\n]s", str)) != '\n'){ 
            for(i = 0; i < strlen(str) ; i++)  
            {
                sum += str[i];     
            }
            reminder = sum%64;         //sum of char then divide by 64 and remainder of sum
            reminder = reminder + 32;  // remainder + 32
            final = reminder;          //change the int to char
            printf("Check sum is %c\n", final); // output
            printf("Enter an abitrarily long string, ending with carriage return > ");
        }
        else
        break;
    }
    return 0;
}

The problem is that if i don't use while loop the program works fine but once you using while it goes into an infinite loop... How can i change this code? I want to keep asking strings until the user presses enter key to exit. Otherwise it should keep asking strings.

scanf does not return a character value, which is what you are currently checking to terminate your loop. It returns the total number of items successfully parsed from the format string. This obviously will not equal '\\n'.

You will need to use strcmp to check if your str contains a newline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM