2012-11-22 57 views
0

似乎无法找到任何关于如何从.txt文件中的特定行中找到信息的信息。 欲行可能是从冰球比赛的结果, 行可能看起来像:查找文本文件中某一行的特定信息

19.00 01.01.2010 TEAM1 - 5的Team2 - 10 2000

20.00 2010年2月20日的Team2 - Team3 7 - 11 3400

19.00 2010年3月30日TEAM1 - Team4 4 - 4 1000

等等...

因此,如果我只想从team3和team4的比赛中获得外线打印?

这是我目前所拥有的,但是如果我想输入2 - 2并获取其中有数字2的每一行。

谢谢

#include <stdio.h> 
#include <string.h> 

int main (void){ 
    char target [ 64 ]; 
    printf("Enter a score:"); 
    scanf("%s",&target); 

    static const char filNavn[] = "text"; 
    FILE *fil = fopen(filNavn, "r"); 
    if (fil != NULL){ 
     char line [ 64 ]; 

     while(fgets(line, sizeof line, fil) != NULL){ 

      if (strstr(line, target) != NULL){ 
       printf("%s\n", line); 
      } 
     } 
     fclose(fil); 
    } 
    else{ 
     perror(filNavn); 
    } 
    return 0; 
} 
+0

你应该列出你想要显示的所有组合和一些文件内容的例子。 –

+0

好吧,我在 – Winkz

回答

0

如果你是如此的确认文件中该行的格式,那么你可以使用sscanf。例如说

int score = atoi(target); 
while(fgets(line, sizeof line, fil) != NULL){ 
int t1, t2, s1, s2; 
sscanf(line, "Team%d vs Team%d %d-%d", &t1, &t2, &s1, &s2); 
if (s1 == score || s2 == score) 
    /* Do something here */ 
} 
+0

多投一行,我应该把它替换成我以前的版本,还是仅仅复制它? – Winkz

+0

您必须根据您的需要更改上述代码。我采用了格式“Team1 vs Team2 2-2”。如果有空间,也包括它们。 –

+0

嗯如果我只想找到结束了2 - 2的比赛呢? – Winkz

0

有些错误我看到:

  1. code-line 7应该是:

    /* Let's leave it easy, there are somethings you must 
        read about safety reading. */ 
    gets(target); 
    

PD:你的目标前添加一个与号(&)如果你想使用这种语法,它应该是,&target[ 0 ];

  1. code-line 12你宣布一个新的变量,它是不是好做,所以我建议,你声明的目标字符串你申报。

  2. 在此示例中,您表示您的数据保存在42 characters的插槽中,因此请扫描相同大小的code-line 12

    char line[ 43 ]. 
    
  3. 在TIS同样的方式,然后你的目标不应该比线code-line 5更大。

    char target[ 43 ]. 
    
  4. 关于strstr()功能,这样工作Cplusplus strstr() behavior description

找到子(的strstr())。返回str1中第一次出现str2的指针,如果str2不是str1的一部分,则返回空指针。

+0

谢谢Alberto,我读的文本文件最后没有.txt文件,当我写.txt时,它不会读取,但是如果我不写它,它会读取。 Atm我拥有它,所以我现在可以找到每场比赛都有相同的结果:)但是我还想要如何找到所有比赛中已经超过3个进球的比赛,如果你能帮助我呢? – Winkz

相关问题