XtenanetX XtenanetX - 3 years ago 155
C Question

C: Break Loop on Empty Input

So I'm writing a program that will loop forever, accepting string inputs until the user just presses enter with no string (along the way, I'm tracking the longest/shortest strings entered). I have this loop:

char stringIn[1000] = {'\0'};
while(1) {
scanf("%[^\n]s", stringIn);
if(stringIn[0] == '\0') {
break;
}

if(strlen(stringIn) > strlen(longString)) {
longString == stringIn;
} else if (strlen(stringIn) < strlen(shortString)) {
shortString == stringIn;
}
i++;
}


Currently this just loops forever. I'm still really new to C, but to me this looks like it should've worked.

Answer Source

Points to note:

  1. You probably mistook the == operator for =, which is assignment. Even so, it wouldn't work because here it would only copy addresses of buffers (which get overwritten) (actually in my code it would throw a compile time errors). For copying strings you wanna use strcpy.
  2. scanf is pretty vulnerable to buffer overflows and leaves the delimiter in the buffer. fgets is a much better choice for reading lines as it takes a buffer length as argument (check this out).
  3. scanf fills a number of items in it's list until characters matching the format string are read. If no chars match, then it doesn't fill stringIn, and hence doesn't append a '\0' at the end, and that's why your code never goes to break;. Instead we can use the return value, which is the number of items of the list that it fills (see here).

Anyway, here is code that does what you want:

int main() {
    char stringIn[1000] = "";
    char longString[2000] = "", shortString[2000] = "";
    int read, firstFlag = 0;
    while(1)  {
        read = scanf("%[^\n]s", stringIn);
        if (read == 0) {
            break;
        }
        // to consume the '\n' left by scanf in the buffer
        getchar();

        if (!firstFlag || strlen(stringIn) > strlen(longString)) {
            strcpy(longString, stringIn);
        } 
        if (!firstFlag || strlen(stringIn) < strlen(shortString))  {
            strcpy(shortString, stringIn);
        }
        firstFlag = 1;
    }    

    printf("%s, %s\n", longString, shortString);
    return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download