简体   繁体   English

实施交流计数器

[英]Implementation of a c counter

I wrote ac program to count the number of time the word "printf" occurs in a specific file (here "document.c"). 我编写了一个ac程序来计算单词“ printf”在特定文件(此处为“ document.c”)中出现的时间。 "document.c" has multiple lines of code. “ document.c”具有多行代码。 What I have done is I started with a while loop to iterate over every lines of the file and then I am reading the characters of each lines inside the for loop by using the function strstr. 我要做的是从while循环开始,迭代文件的每一行,然后使用功能strstr读取for循环中每一行的字符。

It does not print anything with my current code. 它不使用我当前的代码打印任何内容。 Moreove, I think there is some other minor issues because in an older version it used to print but not correctly, it printed a number much more larger than the actual number of "printf" in the document. 此外,我认为还有其他一些小问题,因为在较旧的版本中它可以打印但不能正确打印,它打印的数量比文档中“ printf”的实际数量大得多。

I am also novice in c.thank you! 我也是新手,谢谢!

int counter() {
    FILE * filePointer;
    filePointer = fopen("document.c", "r");
    int counter = 0;
    char singleLine[200];

    while(!feof(filePointer)){
        fgets(singleLine, 200, filePointer);
        for (int i = 0; i < strlen(singleLine); i++){
            if(strstr(singleLine, "printf")){
                counter++;
            }
        }
    }
    fclose(filePointer);
    printf("%d",counter);
    return 0;
}

You're iterating over each character in the input line, and then asking if the string "printf" appears anywhere in the line. 您要遍历输入行中的每个字符,然后询问字符串“ printf”是否出现在行中的任何位置。 If the line contains 5 characters, you'll ask this 5 times; 如果该行包含5个字符,您将询问5次; if it contains 40 characters, you'll ask this 40 times. 如果包含40个字符,您会询问40次。

Assuming that you're trying to cover the case where "printf" can appear more than once on the line, look up what strstr() returns, and use that to adjust the starting position of the search in the inner loop (which shouldn't iterate over each character, but should loop while new "hits" are found). 假设您试图解决“ printf”可能多次出现的情况,请查找strstr()返回的内容,并使用它来调整搜索在内部循环中的开始位置(不应遍历每个字符,但应在找到新的“匹配”时循环播放)。

(Note to up-voters: I'm answering the question, but not providing code because I don't want to do their homework for them.) (致投票者的注意事项:我正在回答问题,但未提供代码,因为我不想为他们做功课。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM