我正在从文件中读取这种类型的行。我想在正斜杠之前提取这个数字 12(或任何其他数字)
12/1000 类状态(直到结束)
现在我的代码只是从文件中提取上面的整行,但我需要正斜杠之前的数字。我怎样才能做到这一点
if (strstr (line,"class states")!=NULL) {
if (file3!= NULL ) {
fprintf(file3, "%s", line);
}
}
您可以使用许多函数来解析您正在查找的行的特定部分:任何一个sscanf
,strchr
(或index
),并且strtok
可能是合适的,具体取决于您要查找的内容。(例如,分隔符是否始终为单个“/”,或者您是否需要处理多字符分隔符)。
在所有情况下,正如 xaxxon 所建议的那样,您首先需要使用类似的东西阅读整行fgets
,然后调用您选择的函数将其拆分。
----edit---- 如果你知道你的号码总是在第一个'/'之前,你可以这样做:
int number;
if (sscanf(line, "%d/", &number) == 1) {
printf("number found = %d\n", number);
} else {
printf("INVALID INPUT\n");
}
"%d/" 是一个模式,它告诉 sscanf 匹配一个十进制数,后跟一个 '/'。sscanf 返回分配的输入值的数量,因此如果它不是“1”,则输入行不是预期的格式。
用于strchr
查找分隔符并一直阅读。
方法很简单......你几乎拥有它:
我们来看一张更完整的图:
int main() {
char line[256]; /* a long enough line */
char *p;
FILE *fin, *fout;
fin = fopen("somefile.txt", "r");
fout = stderr; /* you can change this to another open file later */
while(!feof(fin)) {
fgets(line, sizeof(line), fin);
p = strstr(line, "class states");
if ( p ) { /* we found the line */
/* okay here p is a pointer that points to
* the beginning of the phrase class states but we want just
12 (or whatever) before the /1000 so we use strchr this time */
p = strchr(line, '/'); /* now we are at the first slash */
*p = 0; /* change the slash(/) to NUL and that
* makes the line end at number 12 */
fprintf(fout, "%s\n", line);
}
}
}
这是一种稍微干净的方法,带有一些错误检查。请注意,我颠倒了 if (p) 逻辑以避免大块的选项卡式代码。
int main() {
char line[256]; /* a long enough line */
char *p;
FILE *fin, *fout;
fin = fopen("somefile.txt", "r");
if ( !fin ) {
fprintf(stderr, "Unable to open `somefile.txt' for reading\n");
return -1;
}
fout = fopen("savedfile.txt", "w");
if ( !fout ) {
fprintf(stderr, "Unable to open `savedfile.txt' for writing\n");
return -1;
}
while(!feof(fin)) {
fgets(line, sizeof(line), fin);
p = strstr(line, "class states");
if ( !p ) { /* we did not find the line */
continue;
}
/* everything below this happens when we find the line */
/* okay when we get here p is a pointer that points to
* the beginning of the phrase class states but we want just
12 (or whatever) before the /1000 so we use strchr this time */
p = strchr(line, '/'); /* now we are at the first slash */
if ( !p ) {
fprintf(stderr, "Didn't find a slash in `%s'\n", line);
continue; /* go on to the next line */
}
*p = 0; /* change the slash(/) to NUL and that
* makes the line end at number 12 */
fprintf(fout, "%s\n", line);
}
fclose(fout);
return 0;
}