gpt4 book ai didi

c++ - 使用C在文本中搜索一个词,并显示该词后的信息

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:37:49 26 4
gpt4 key购买 nike

假设我有一个这样的文本文件:

用户:约翰

设备:12345

日期:2012 年 12 月 12 日

编辑:

我有我的代码可以成功搜索一个词,并显示该词之后的信息。但是,当我尝试编辑代码以搜索 2 或 3 个词并在它们之后显示信息而不是仅显示 1 个词时,我无法让它工作。我曾尝试将代码添加到同一个 while 循环中,并为另一个词创建一个新的 while 循环,但两者都不起作用。一定有什么地方我做错了/没做。

请指教,谢谢!

这是我的代码:

 #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {

char file[100];
char c[100];

printf ("Enter file name and directory:");
scanf ("%s",file);

FILE * fs = fopen (file, "r") ;
if ( fs == NULL )
{
puts ( "Cannot open source file" ) ;
exit( 1 ) ;
}

FILE * ft = fopen ( "book5.txt", "w" ) ;
if ( ft == NULL )
{
puts ( "Cannot open target file" ) ;
exit( 1 ) ;
}

while(!feof(fs)) {
char *Data;
char *Device;
char const * rc = fgets(c, 99, fs);

if(rc==NULL) { break; }

if((Data = strstr(rc, "Date:"))!= NULL)
printf(Data+5);

if((Data = strstr(rc, "Device:"))!=NULL)
printf(Device+6);
}



fclose ( fs ) ;
fclose ( ft ) ;

return 0;

}

最佳答案

好的,希望我这次能清除它。对不起,如果我有时会感到困惑,但我的英语不是最好的。

我将在评论中解释实现:

#define BUFFSIZE 1024
int main()....

char buff[BUFFSIZE];
char delims[] = " "; /*Where your strtok will split the string*/
char *result = NULL;
char *device; /*To save your device - in your example: 12345*/
char *date; /*To save the date*/
int stop = 0;

fp = fopen("yourFile", "r");

while( fgets(buff, BUFFSIZE,fp) != NULL ) /*This returns null when the file is over*/
{
result = strtok( buff, delims ); /*You just need to do reference to buff here, after this, strtok uses delims to know where to do the next token*/

while(result != NULL){ /*Strtok returns null when finishes reading the given string*/
if(strcmp(result,"Device")==0){ /*strcmp returns 0 if the strings are equal*/
result = strtok(NULL, delims); /*this one gets the 12345*/
device = (char*)malloc((strlen(result)+1)*sizeof(char)); /*Alocate the right amount of memory for the variable device*/
strcpy(device, result); /*Now, device is "12345"*/
}
/*Here you do the same but for the string 'Date'*/
if(strcmp(result,"Date")==0){ /*strcmp returns 0 if the strings are equal*/
result = strtok(NULL, delims); /*this one gets the 12345*/
date = (char*)malloc((strlen(result)+1)*sizeof(char)); /*Alocate the right amount of memory for the variable device*/
strcpy(date, result); /*Now, device is "12/12/12"*/
}
/*And you can repeat the if statement for every string you're looking for*/
result = strtok(NULL,delims); /*Get the next token*/
}
}

/*No strtok necessary here */

...

希望这对您有所帮助。

关于c++ - 使用C在文本中搜索一个词,并显示该词后的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14062176/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com