My code is this. I am reading a file, comparing the word entered by user from data in file and then want to print the next two words from file. How can I do that?
#include <stdio.h>
#include <string.h>
int main()
{
//Open the file for reading
FILE *in = fopen("data.txt", "r");
char str[]="file1.txt";
//fgets buffer
char buffer[100];
//Pieces of string tokenized
char * stringPiece;
//int for comparing strings
int compare=2;
//While loop. Getting lines from file
while ( fgets(buffer, sizeof(buffer), in) != NULL ){
fgets(buffer, 100, in);
// printf("%s\n", buffer);
stringPiece = strtok (buffer,",");
while (stringPiece != NULL){
printf("%s\n",stringPiece);
compare=strcmp(stringPiece,str);
if (compare==0){printf("HELP");}
//printf("%s\n",stringPiece);
stringPiece = strtok (NULL, " ");
}
}
//Close file
fclose(in);
return 0;
}
I can find the word in file same as what user entered but unable to print the next two words from file. File name is data.txt.
Code formatted to be legible (use vim and =% on the open brace of the main() function, mostly).
#include <stdio.h>
#include <string.h>
int main(void)
{
//Open the file for reading
FILE *in = fopen("data.txt", "r");
char str[]="file1.txt";
//fgets buffer
char buffer[100];
//Pieces of string tokenized
char * stringPiece;
//int for comparing strings
int compare=2;
//While loop. Getting lines from file
while ( fgets(buffer, sizeof(buffer), in) != NULL ){
fgets(buffer, 100, in);
// printf("%s\n", buffer);
stringPiece = strtok (buffer,",");
while (stringPiece != NULL){
printf("%s\n",stringPiece);
compare=strcmp(stringPiece,str);
if (compare==0){printf("HELP");}
//printf("%s\n",stringPiece);
stringPiece = strtok (NULL, " ");
}
}
//Close file
fclose(in);
return 0;
}
sample of find the word and next two words get