adohertyd
adohertyd

Reputation: 2689

While loop repeating but don't know why

I am writing a program that reads the first 20 lines of a text file. When the first 20 lines are read, the user is given the option to continue reading the next 20 lines or to quit the program. What's happening me however is it prints the 20 lines, the user prompt comes up, and then it automatically prints the next 20 lines, without waiting for the user's input. After that, it will print the user prompt and then wait for the input. I know it's a simple issue but I'm not seeing it! I've amended the code a little bit as per replies to my question so far:

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

int main(void)
{
FILE *fp;
char fname[20];
char c, input;
int line;
line = 0;

    printf("Please enter the name of the file you wish to view\n");
    scanf("%s", fname);

    fp = fopen(fname, "r");

    if (fp == NULL)
    {
    printf("The file did not open correctly");
    exit(0);
    }

    else
    {
    printf("The file opened correctly\n");
    }

        while(c != EOF && input != 'q')
        {   
            c = getc(fp);
            printf("%c", c);

                if  (c == '\n')
                {
                line++;

                    while (line==20)
                    {
                    line = 0;
                    printf("Press return to view the next 20 lines or press q to quit:");
                    scanf("%c", &input);

                        if (input == 'q')
                        {               
                            return 0;
                        }

                        else if (input == '\n')
                        {
                            line++;
                        }
                    }
                }
        }
return 0;
}

Upvotes: 0

Views: 354

Answers (3)

puikos
puikos

Reputation: 300

You should use an fgets of stdin instead of scanf, you can specify the number of caracters you need to read and it's more secure.

Upvotes: 0

Tudor
Tudor

Reputation: 62439

line = line++;

Postincrement, your line is always 0. Use just:

line++;

Edit: Ok, so this is not the problem. I've run your program and the problem is that when you enter the file name to the first scanf, you press enter so the program reads it. For some reason this enter (or newline) is read inside the second scanf as the input. Just add a dummy scanf after the first one to absorb this newline:

printf("Please enter the name of the file you wish to view\n");
scanf("%s", fname);
scanf("%c", &input); // dummy scanf

Upvotes: 5

Most importantly, learn to enable all warnings and debug information (on linux, with gcc -Wall -g) and learn how to use a debugger (like gdb on Linux).

You really cannot learn to code in C without both.

Upvotes: 1

Related Questions