我的代码是这样的。我正在读取一个文件,比较用户从文件中的数据输入的单词,然后想从文件中打印接下来的两个单词。我怎样才能做到这一点?
#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;
}
我可以在文件中找到与用户输入的相同的单词,但无法从文件中打印接下来的两个单词。文件名为 data.txt。
格式化为清晰易读的代码(主要在函数的左大括号上使用vim
和)。=%
main()
#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;
}