Reputation: 495
I'm trying to read in a file and then output the file by characters. I want the user to enter a number which will be the number of lines to be displayed.
Without the following line, my code will display the entire text file. if (y == lineCount) break;
This line is supposed to break the loop when the number of newline characters counted is equal to the number the user entered.
I can count the number of newLine characters and display that but when I try to break the loop after reaching that certain number of newLines, the code breaks after 1 character
#include <stdio.h>
int main ( int argc, char *argv[] )
{
FILE *file = fopen( argv[1], "r" );
int lineCount, x, y;
printf("enter a number of lines of lines to be displayed\n");
scanf("&d", &y);
while ( ( x = fgetc( file )) != EOF ) //read characters
{
printf( "%c", x ); //print character
if (x == '\n') //check for newline character
lineCount++;
if (y == lineCount) //check for newLine character
break; //??? y = lineCount after 1 character???
}
printf( "%d lines in the text file\n", lineCount ); //testing the newline characters was being read
fclose( file );
}
Upvotes: 0
Views: 483
Reputation: 10937
You want scanf("%d", &y)
instead of scanf("&d", &y)
.
Also you never initialize lineCount
, so it's initial value isn't garunteed to be 0.
Upvotes: 0