I've been coding a program to write data into a textfile and practice data processes in c, and find data from there, every data is stored as lines.There are lines, and data is stored line by line, such as:
student name student surname student phone etc.
When i take an input of "student name" it starts to print without printing the name itself, prints what comes after it, same happens if i search for surname, only phone will be printed out.
How can i solve this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *filePtr;
filePtr=fopen("std.txt","r");
char char_input[50];
char string[500];
printf("%s","Please give an input of the phone number\n");
scanf("%s",char_input);
while(!feof(filePtr)){
fscanf(filePtr,"%s",string);
if(strcmp(string, char_input)== 0){
fgets(string,500,filePtr);
puts(string);
}
}
fclose(filePtr);
}
Text file:
Andrew Brooks 865 965 55
Input:
Andrew
Output:
Brooks 865 965 55
Desired output:
Andrew Brooks 865 965 55
CodePudding user response:
Instead of incorrectly using feof() and fscanf(filePtr,"%s", ... to incorrectly read a line. Use fgets() to read a line of the file and convert to a string.
Test the return value of
fgets()to see if input occurred.Use
strstr()to look for a matching sub-string withinstring.
Example:
while (fgets(string, sizeof string, filePtr)) {
if (strstr(string, char_input)){
fputs(string, stdout);
}
}
