似乎找不到任何信息,我如何从一个.txt文件中的一个特定的行找到信息。就像曲棍球比赛的结果一样,这条线看起来可能是:
Team1 - Team2 5- 10 2000 Team2 - Team3 7- 11 3400 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;
}发布于 2012-11-22 09:59:56
如果您非常确定文件中行的格式,那么可以使用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 */
}发布于 2012-11-22 12:04:39
我看到了一些错误:
code-line 7中,应该是:
/*,让我们简单地说,有一些东西你必须读到关于安全阅读。*/获取(目标);PD:如果您想使用应该使用的语法,则在目标之前添加一个符号(&),&target[ 0 ];
code-line 12中,您声明了一个新变量,这样做是不好的,所以我建议您在声明目标字符串的地方声明它。42 characters的插槽中,所以扫描大小相同的code-line 12。
43号线。code-line 5大。
目标43。strstr()函数,它的工作方式是Cplusplus strstr()行为描述找到子字符串( strstr() )。返回指向str2在str1中的第一次出现的指针,如果str2不是str1的一部分,则返回空指针。
https://stackoverflow.com/questions/13509847
复制相似问题