I want to code a program that scans each line and print it. Also this process should keep on when the specific line was detected. Here is my file content :
1
2
3
4
5
6
7
8
9
and the code :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *file;
int main(){
file=fopen("numbers.txt","r");
char line[10];
while(1){
fgets(line,10,file);
printf("%s \n\n",line);
if(strcmp(line,"6")) break;
}
fclose(file);
system("pause");
return 0;
}
But loop doesn't work and print only first line. Where is the problem?
strcmp
returns non-zero if the strings do not match, and zero if they do.
Change your test:
if( 0 == strcmp(line,"6") ) break;
I think you mean if(! strcmp(line,"6")) break;
(strcmp returns 0 when the strings are equal)
This should work:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
FILE *file;
int main(){
file=fopen("numbers.txt","r");
char line[10];
while(1){
fgets(line,10,file);
printf("%s \n\n",line);
if(!strcmp(line,"6\n")) break;
}
fclose(file);
system("pause");
return 0;
}
You had two problems, first strcmp returns 0 if strings are equal, second fgets returns new line mark '\\n', so you have to match it too.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.