Home > Back-end >  How do I exit a loop without using a break statement?
How do I exit a loop without using a break statement?

Time:08-29

    int count = 0;
    // read characters from the standard input
    while ((count != max_string_length) && (string[count] = getchar())) {
        // until a newline or EOF reached
        if ((string[count] == '\n' || string[count] == EOF)) {
            string[count] = 0;
            break;
        }
        count  ;
    }

This is my code, It reads a string from standard input and returns the length of the string, and the string terminates and ignores either EOF or a newline (\n) characters. However, I'm not allowed to use a break statement, I'm wondering if is there a way to exit the loop without using a break statement.

CodePudding user response:

... is there a way to exit the loop without using a break statement (?)

Yes. Perform all 3 tests in the loop's controlling expression and none in the body of the loop. No loop test needed in the loop's body.

  • Save the 257 different response values of getchar() into an int to maintain the value's distinctiveness.

  • Append a null character after the loop.

  • Use size_t rather than int to handle all possible string sizes.

A more typical read line example code:

// int count = 0;
size_t count = 0;
int ch;

while ((count < max_string_length) && ((ch = getchar()) != '\n') && (ch != EOF)) {
  string[count  ] = ch;
}

string[count] = `\0`;

If the limit represents the size of the buffer and not its maximum length as returned from strlen(), use a better name and alternate code.

while ((count   1 < string_size) && ...

CodePudding user response:

To check for EOF you need to save the result of getchar in int variable. If string can accommodate max_string_length characters (including null terminating character) you need to check where to place the null terminating character.

    size_t count = 0;
    int c;
    // read characters from the standard input
    while ((count < max_string_length - 1) && (c = getchar()) != EOF && c != '\n') 
    {
        string[count  ] = c;
    }
    
    string[count] = 0;

CodePudding user response:

Try using return 0 instead of break

  • Related