Press Enter to Continue or Any to Exit C

  1. #1

    lyelt is offline

    Registered User


    Press Enter to Exit a Loop?

    So I have been assigned a program that counts keystrokes, alphabetical characters, and vowels. I have the program working as desired but I just can't figure out how to make it end upon ONLY the "return" key being pressed. I am quite new to programming in general so I hope the code is formatted and commented so as to make assisting me easier. Thanks for any help!

    Code:

    #include <stdio.h> #include <stdlib.h> #include <ctype.h>   int main ( void ) {       while(1)     {         int count = 0;        // Initializes the variable for number of keystrokes         int alpha = 0;        // Initializes the variable for alphabetic characters         int vowels = 0;       // Initializes the variable for number of vowels         char sentence;               printf( "Enter your sentence: ");         // Prompt for sentence           while ((sentence = getchar()) != '\n')    // Evaluate all characters until enter is pressed         {               switch(sentence)                      // Increment count             {                 case ('\n'): return 0;            // This is what I thought would cause the program to exit upon hitting enter, but I'm not sure what to change to make                  default: ++count; break;               }               switch (isalpha(sentence))            // Increment alpha when character is alphabetical             {                 case 0: break;                    // Do nothing when character is not alphabetical                 default: ++alpha; break;             }               switch (tolower(sentence))            // Increment vowels when character is a vowel (allow for upper or lower case)             {                 case ('a'): case ('e'): case ('i'): case ('o'): case ('u'): ++vowels;                 break;                 default: break;             }         }           printf( "Keystrokes:       %4.0d\n", count);     // Print results         printf( "Alpha Characters: %4.0d\n", alpha);         printf( "Vowels:           %4.0d\n", vowels);     }         return 0; }


  2. #2

    anduril462 is offline

    Registered User


    Yes, it's well formatted and indented, thank you for that. I would suggest fewer blank lines (I know the forum sometimes adds some, but still).

    Not sure what you mean by "ONLY the return key being pressed". I type a sentence, press enter and it terminates. Do you mean an empty line of input with just a return ('\n')? For that you have two options:
    1. Read a whole line with fgets. If the line is empty, except for a '\n', then you quit, otherwise you report statistics.
    2. Set a flag that tracks whether there were any non-newline chars entered. After your inner while loop, use that flag to decide if you need to break out of the outer while loop.

    You don't need parentheses around your switch case values. In fact, it's uncommon and (IMO) clutters up the code with unnecessary punctuation. As an example, case 'a': should be fine.

    sentence is a poor name for a variable that contains a single character. ch would be fine. I'll use that from here on out.

    break; only breaks you out of the innermost loop/switch. Furthermore, you can't actually get to that line. The condition of the while loop prevents you from entering the loop if ch is a '\n' ("return" key).

    I'm not a fan of infinite loops with break statements unless they make the code significantly easier to read/understand. It doesn't in this case. Consider a do-while loop for the outside, which will always execute once -- that is, the user always has a chance to enter a sentence or an empty line (just '\n').

    Code:

    do {     while ((ch = getchar...) {     } } while (user entered something other than just a newline);


  3. #3

    lyelt is offline

    Registered User


    Quote Originally Posted by anduril462 View Post

    Yes, it's well formatted and indented, thank you for that. I would suggest fewer blank lines (I know the forum sometimes adds some, but still).

    Not sure what you mean by "ONLY the return key being pressed". I type a sentence, press enter and it terminates. Do you mean an empty line of input with just a return ('\n')? For that you have two options:
    1. Read a whole line with fgets. If the line is empty, except for a '\n', then you quit, otherwise you report statistics.
    2. Set a flag that tracks whether there were any non-newline chars entered. After your inner while loop, use that flag to decide if you need to break out of the outer while loop.

    You don't need parentheses around your switch case values. In fact, it's uncommon and (IMO) clutters up the code with unnecessary punctuation. As an example, case 'a': should be fine.

    sentence is a poor name for a variable that contains a single character. ch would be fine. I'll use that from here on out.

    break; only breaks you out of the innermost loop/switch. Furthermore, you can't actually get to that line. The condition of the while loop prevents you from entering the loop if ch is a '\n' ("return" key).

    I'm not a fan of infinite loops with break statements unless they make the code significantly easier to read/understand. It doesn't in this case. Consider a do-while loop for the outside, which will always execute once -- that is, the user always has a chance to enter a sentence or an empty line (just '\n').

    Code:

    do {     while ((ch = getchar...) {     } } while (user entered something other than just a newline);

    Thank you for your advice. As for "ONLY the return key being pressed", I mean I need the program to end when the user inputs nothing but a newline '\n'. Also, my instructor prefers that I use complete words for variables despite "sentence" being only a character, but I will use "ch" here for consistency's sake.

    I'm not sure if I completely understand your suggestions. I don't believe I can use fgets, so how exactly would I set up a flag in the inner loop to break out of the outer loop?

    I used an infinite loop because I have to keep reading inputs and displaying the outputs until just a newline is entered. If I can obtain that result with a do-while loop, that would be just as effective.

    I apologize in advance if this is completely incorrect, but this is what I gathered from your bit of code.

    Code:

    #include <stdio.h> #include <stdlib.h> #include <ctype.h>   int main ( void ) {     do     {         int count = 0;        // Initializes the variable for number of keystrokes         int alpha = 0;        // Initializes the variable for alphabetic characters         int vowels = 0;       // Initializes the variable for number of vowels         char ch;           printf( "Enter your sentence: ");         // Prompt for sentence           while ((ch = getchar()) != '\n')    // Evaluate all characters until enter is pressed         {               switch(ch)                      // Increment count             {                 case ('\n'): return 0;            // Can this be completely deleted then?                         default: ++count; break;               }               switch (isalpha(ch))            // Increment alpha when character is alphabetical             {                 case 0: break;                    // Do nothing when character is not alphabetical                 default: ++alpha; break;             }               switch (tolower(ch))            // Increment vowels when character is a vowel (allow for upper or lower case)             {                 case 'a': case 'e': case 'i': case 'o': case 'u': ++vowels;                 break;                 default: break;             }         }           printf( "Keystrokes:       %4.0d\n", count);     // Print results         printf( "Alpha Characters: %4.0d\n", alpha);         printf( "Vowels:           %4.0d\n", vowels);     }     while(???); // What would I place here?       return 0; }


  4. #4

    anduril462 is offline

    Registered User


    Good that your prof requires whole-word identifiers, getting in the habit of good variable/funciton names is important. Instead of ch, let's use character_read. That's quite descriptive and accurate.

    You're definitely on the right track.

    The '\n' switch bit can be completely deleted (lines 23-29 in post #3).

    As for the condition of the do-while: what if you had a variable named number_of_characters_read which counted the number of non-newline characters in each line? Does that give you a hint of how to exit the loop?

    One more note, switch doesn't make sense for your isalpha check, a basic if statement would be better here (not even an if-else since you don't do anything if it's non-alpha). switch is best used when there are a number of different cases to cover, as you do with your vowel check.


  5. #5

    lyelt is offline

    Registered User


    Quote Originally Posted by anduril462 View Post

    Good that your prof requires whole-word identifiers, getting in the habit of good variable/funciton names is important. Instead of ch, let's use character_read. That's quite descriptive and accurate.

    You're definitely on the right track.

    The '\n' switch bit can be completely deleted (lines 23-29 in post #3).

    As for the condition of the do-while: what if you had a variable named number_of_characters_read which counted the number of non-newline characters in each line? Does that give you a hint of how to exit the loop?

    One more note, switch doesn't make sense for your isalpha check, a basic if statement would be better here (not even an if-else since you don't do anything if it's non-alpha). switch is best used when there are a number of different cases to cover, as you do with your vowel check.

    I cannot thank you enough! I seem to have gotten it working exactly as I need it to. I greatly appreciate your help!

    Here is my final (I hope) code. If you have any other suggestions or if anything is glaringly incorrect, feel free to add (though it seems to be working fine).

    Code:

    #include <stdio.h> #include <stdlib.h> #include <ctype.h>   int main ( void ) {     int number_of_characters_read;      // Variable to test for characters being entered       do     {         int count = 0;        // Initializes the variable for number of keystrokes         int alpha = 0;        // Initializes the variable for alphabetic characters         int vowels = 0;       // Initializes the variable for number of vowels         char character_read;             printf( "Enter your sentence: ");               // Prompt for sentence             while ((character_read = getchar()) != '\n')    // Evaluate all characters until enter is pressed         {             ++count;                                    // Increment count in all cases               if (isalpha(character_read) != 0)           // Increment alpha when character is alphabetical             {                 ++alpha;             }               switch (tolower(character_read))            // Allow for upper or lower case input             {                 case 'a': case 'e': case 'i': case 'o': case 'u': ++vowels;     // Increment vowels when character is a vowel                 break;                 default: break;             }         }           if (count == 0)      // If no characters are entered (ie. just a newline), set number of characters read == 0 and do not print results         {             number_of_characters_read = 0;             break;         }           printf( "Keystrokes:       %4.0d\n", count);     // Print results         printf( "Alpha Characters: %4.0d\n", alpha);         printf( "Vowels:           %4.0d\n", vowels);     }     while(number_of_characters_read != 0);     // Continue looping until nothing is read (ie. just a newline is entered).         return 0; }


  6. #6

    WoodSTokk is offline

    Registered User


    You set the variable 'number_of_characters_read' to 0 if the variable 'count' is also 0.
    In this case you can use 'count' directly, like:

    Code:

                          if (count == 0) break;      // If no characters are entered (ie. just a newline), do not print results, break out of loop
    and the condition of your do-while-loop:

    Code:

                          while(count != 0);     // Continue looping until nothing is read (ie. just a newline is entered).


  7. #7

    anduril462 is offline

    Registered User


    With WoodSTokk's comment, you'll be all set. I do have a few suggestions on readability -- these are style issues, not functional issues:

    Code:

    if (isalpha(character_read) != 0)
    I find it far more readable if you drop the != 0

    Code:

    if (isalpha(character_read))
    Also, for your switch statement, don't put all 5 letters on a line. Especially since you have a comment on that line, it makes the line too long. 80 characters is pretty standard, up to 120 is widely accepted. Beyond that is generally considered too long. Also, it's a good idea to put a comment stating that you explicitly intend for the code to fall through to the subsequent cases, just for clarity:

    Code:

    switch (tolower(character_read)) {     case 'a':  // fall through     case 'e':  // fall through     case 'i':  // fall through     case 'o':  // fall through     case 'u':         ++vowel;         break; }


  8. #8

    ErtMasterFlex is offline

    Registered User


    lyelt, do you have this class with a professor that has the initials J.B.?


austinwoned1939.blogspot.com

Source: https://cboard.cprogramming.com/c-programming/164790-press-enter-exit-loop.html

0 Response to "Press Enter to Continue or Any to Exit C"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel