Home > Blockchain >  While loop quitting only when q is entered twice
While loop quitting only when q is entered twice

Time:02-05

How do I terminate the while loop without needing the user to enter q twice?

I think I have an input buffer somewhere, but I am not sure where my problem is.

#include <stdio.h>
#include <string.h>
int main(void)
{
    int Length, fLength, iLength;
    char sObject [25];
    printf("Enter object and object length in inches (q to quit); \n");
    while (scanf("$s %d", sObject, &Length) > 1) {
        fLength = Length / 12;
        iLength = Length % 12;
        printf("The length of %s is %d foot %d inches\n", sObject, fLength, iLength); 
        printf("Enter object and object length in inches (q to quit); \n");
    }
    return 0;
}

Here is an example of my output.

Enter object and object length in inches (q to quit);
bat 100
The length of bat is 8 foot 4 inches
Enter object and object length in inches (q to quit);
q
q

CodePudding user response:

The first q matches the $s conversion specification, the second q causes the %d to fail, hence scanf() returns 1 and the loop is exited.

You should read a full line of input at a time, test for the exit command and attempt to convert with sscanf() otherwise

Also note that the split into feet and inches is incorrect: you should compute inches before dividing fLength. Using 2 extra variables is more readable and less error prone.

Here is a corrected version:

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

int main(void) {
    char buf[100];
    char object[25];
    int length;

    for (;;) {
        printf("Enter object and object length in inches (q to quit):\n");
        if (!fgets(buf, sizeof buf, stdin)) {
            /* end of file or read error */
            break;
        }
        if (!strcmp(buf, "q\n")) {
            /* user typed q enter */
            break;
        }
        if (sscanf(buf, "$s %d", object, &length) == 2) {
            int feet = length / 12;
            int inches = length % 12;
            printf("The length of %s is %d foot %d inches\n",
                   object, feet, inches); 
        } else {
            printf("invalid input: %s\n", buf);
        }
    }
    return 0;
}

CodePudding user response:

If I have understood correctly then rewrite the while statement for example the following way

while (scanf("$s", sObject) == 1 && strcmp(sObject, "q") != 0 && scanf("%d", &Length) == 1) {
  • Related