【发布时间】:2021-03-11 15:42:14
【问题描述】:
我在处理来自文件的一行的标记化字符串时遇到了一些问题。我想打印找到令牌的行,但我似乎找不到解决方法。请忽略文件部分的输出以及作者、类和方法 if 语句,因为我已将它们整理出来。
例如,我希望它从这一行打印: @return the matric 仅此部分:the matric
代码:
#include <stdio.h>
#include <string.h>
int main (int argc, char **argv)
{
char line [1000];
char *delimeters = ".,; \t\n";
int total_lines = 0;
int total_comments = 0;
int nonblank_lines = 0;
FILE *input = fopen (argv[2], "r");
FILE *output = fopen (argv[4],"w");
while(fgets(line,1000,input) != NULL)
{
char *word = strtok(line, delimeters);
total_lines++;
if(word != NULL)
{
nonblank_lines++;
}
if(word != NULL && strcmp(word,"/**") == 0)
{
total_comments++;
}
while(word != NULL)
{
if(word != NULL && strcmp(word,"@author") == 0)
{
char *author_name = strtok(NULL, delimeters);
char *author_surname = strtok(NULL, delimeters);
printf ("Author: %s %s\n", author_name, author_surname);
}
if(word != NULL && strcmp(word,"public") == 0)
{
char *jmp = strtok(NULL, delimeters);
if(jmp != NULL && strcmp(jmp,"class") == 0)
{
char *class_name = strtok(NULL, delimeters);
printf ("Class %s\n", class_name);
}else{
char *method_name = strtok(NULL, delimeters);
printf ("Method %s\n", method_name);
}
}
if(word != NULL && strcmp(word,"@return") == 0)
{
printf("Enters IF 4\n");
char *return_value = strtok(NULL, delimeters);
printf ("Returns: %s\n", return_value;
}
/*if(word != NULL && strcmp(word,"@param") == 0)
{
printf("Enters IF 5\n");
char *parameters = strtok(NULL, delimeters);
printf("Parameter: %s\n", parameters);
//int param_found
}*/
word = strtok(NULL, delimeters);
}
}
printf ("The total number of lines is %d\n", total_lines);
printf ("The total number of non-blank lines is %d\n", nonblank_lines);
printf ("The total number of comments is %d\n", total_comments);
fclose(input);
fclose(output);
return 0;
}
【问题讨论】:
-
如果您的行中的第一个标记不是
@return(在该行示例中是*),您的内部while循环将永远不会转到下一个标记,因为if语句条件将是假的。 -
但我得到的输出是
the。 -
这意味着您没有提供一些信息。使用您编写的代码和包含您提到的行的文件,您的程序将进入内部 while 循环的无限循环,因为它的条件结果没有任何改变。
-
我添加了所有我拥有的代码。
-
如果您的目标是从每一行返回
@word之后的其余单词,那么您需要在每个if语句中使用 while 循环迭代strtok()当前行中的其余单词并一一输出。现在你只输出第一个。