user12696730
user12696730

Reputation:

2 while loops in a function in C

Is it possible to run 2 while loops in the same function? Only one of the while loops works. If I remove the first the one, the second one will work and if I remove the second one, the first one will work.

#include <stdio.h>
#include <stdlib.h>
#define FILE_NAME "results.txt"

void analyseText(int character[], int i, FILE *fptr, int *sum, int a)
{
    while ((i = fgetc(fptr)) != EOF)
    {
        if (i >= 'a' && i <= 'z')
            character[(i - 'a')]++;
        if (i >= 'A' &&  i <= 'Z')
            character[(i - 'A')]++;

        for (int i = 0; i < 26; i++)
        {
            printf("%c: %d\n", i + 'a', character[i]);

        }
        while (1)
        {
            int result = fscanf(fptr, "%d", &a);
            if (result == EOF) {
                break;
            }
            else if (result == 1) {
                *sum += a;
            }
            else {

                fscanf(fptr, "%*c");
            }
        }
    }
}

Upvotes: 0

Views: 1902

Answers (2)

Alexandru Botolan
Alexandru Botolan

Reputation: 78

I've ran your program and it seems the second while loop terminates the function. The second while loop will read the characters from the file and will do so until it reach the end, then will exit. Both while loop executes, but the first one executes only once and the second executes till will reach the end of the file. Maybe it is a logic bug there?

Also, are you trying to read some numbers in the second loop, the result will never pe 1 if there are only characters in the file.

Upvotes: 2

pmg
pmg

Reputation: 108938

You have an (almost) infinite loop inside an (almost) infinite loop, with just about the same stop condition for both.

One of them will run "forever" and when it triggers the stop condition the other will also stop, giving the appearance of just one of the loops running.

2 loops

enter infinite loop1
    do some stuff one once
    enter infinite loop2
        do some stuff two "forever"

when you remove the inner loop

enter infinite loop1
    do some stuff one "forever"

when you remove the outer loop

enter infinite loop2
    do some stuff two "forever"

Upvotes: 0

Related Questions