0
#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.

lorenz
  • 4,538
  • 1
  • 27
  • 45
MoshMouse
  • 1
  • 1
  • 1
  • 2
    hope you want to do same thing.....http://stackoverflow.com/questions/16621020/exit-out-of-a-loop-after-hitting-enter-in-c – µtex Nov 11 '14 at 20:16
  • Can you explain your question a bit better. First you say "enter a string ending with carriage return ... and keep asking strings" but then you say you want it to exit when they press Enter. Enter is the same as carriage return. – M.M Nov 11 '14 at 22:15
  • Okay.. it is a program that get user input that is string like EX) "sadjksajkdjakdjkslajdklsajdksajsdlkajks" each character has its own ascii code which is number. we add all of each char as integers and divide by 64 that gives you remainder. Remainder will be added 32(DEC) then convert to char output. and it while loop should keep asking string from users until user press "enter". so basically enter is used to exit the while loop. – MoshMouse Nov 12 '14 at 01:05

1 Answers1

0

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.