#include <stdio.h>
int main()
{
FILE *file;
char line_text[100];
int user_line= 0;
scanf("%d", &user_line);
file = fopen("words.txt", "r");
for(int i = 1; i <= user_line;i++)
{
if((i = user_line))
{
fgets(line_text, 100 , file);
printf("%s", line_text);
}
}
fclose(file);
return 0;
}```
in this code, the only problem is the for loop
the if statement doesn't do anything as it runs once and that's it
but IDK how to make an if statement affect what line to read first
#if statement only works once and only reads the first line
50 messages · Page 1 of 1 (latest)
When your question is answered use !solved to mark the question as resolved.
Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.
if statement runs once becuase you have (i = user_line) rather than (i == user_line)
= is assignment
== is comparison
in c assignment is an expression
so you can accidentally write it inside the if
its a common bug
what happens here is that you go into the first loop iteration, you assign i with user_line, it increments i, it does the loop check: i <= user_line
well i is now user_line + 1 and so user_line + 1 <= user_line if false
so it exits the loop in the second iteration
I know I just need help with a new if statement that can help me with that
still does that the issue is that it runs once and doesn't affect the amount of lines read
did you save the file and rebuild
yup
wait
wtf is the if
for(int i = 1; i <= user_line;i++)
{
if((i == user_line))
you want to run a loop from i <= user_line
but then you only enter the if when i == user_line
since i is counting from 1 upwards it is only equal to user_line once
so the if is only true once
yeah I know
The problem is you have fgets(line_text, 100 , file); inside the if
which means you only read 1 line
when you actually want to read lines continually, until you reach user_line
I assume
no just the line that corresponds to user_line
you can't just read 1 line
you don't know where that line is until you find all the previous end of lines
files are not organised by line they are organised by characters. The only way to find the end of a line is to find an \n character
other programming languages may seem to magically get around this
but they don't
they too read the entire file looking for \ns until they find them, and that then the next line
so can you help me on how to take out previous lines?
you just read them
fgets reads per line
so if you call fgets itll either get to the end of the line, or it will fill the buffer, or it will reach the end of the file
you can probably assume its going to read the entire line in this case, so you just call fgets continually until you reach the line you want
I know
I just need help with getting to take out the previous lines of text