[英]Counting strings in C, using fgets and strstr
这是作业的一部分,因此说明很清楚,除指定的内容外,不允许使用其他任何内容。
这个想法很简单:
1)创建一个结构数组,其中包含一个字符串和一个计数
2)计算字符串在每个结构中的出现并将其存储在该结构中
3)打印字符串及其出现的次数
我被明确告知要使用fgets和strstr函数
到目前为止,这就是我所得到的,
#define MAX_STRINGS 50
#define LINE_MAX_CHARS 1000
int main(){
int n = argc - 1;
if (n > MAX_STRINGS) {
n = MAX_STRINGS;
}
Entry entries[MAX_STRINGS];
char **strings = argv+1;
prepare_table(n, strings, entries);
count_occurrences(n, stdin, entries);
print_occurrences(n, entries);
}
void prepare_table (int n, char **strings, Entry *entries) {
// n = number of words to find
// entries = array of Entry structs
for (int i = 0; i < n; i++){
Entry newEntry;
newEntry.string = *(strings + 1);
newEntry.count = 0;
*(entries + i) = newEntry;
}
}
void print_occurrences (int n, Entry *entries) {
for (int i = 0; i < n; i++){
printf("%s: %d\n", (*(entries + i)).string, (*(entries + i)).count);
}
}
void count_occurrences (int n, FILE *file, Entry *entries) {
char *str;
while (fgets(str, LINE_MAX_CHARS, file) != NULL){
for (int i = 0; i < n; i++){ // for each word
char *found;
found = (strstr(str, (*(entries + i)).string)); // search line
if (found != NULL){ // if word found in line
str = found + 1; // move string pointer forward for next iteration
i--; // to look for same word in the rest of the line
(*(entries + i)).count = (*(entries + i)).count + 1; // increment occurrences of word
}
}
}
}
我知道我的prepare_table和print_occurrences函数可以正常工作。 但是,问题出在count_occurrences函数上。
已经给我提供了一个要运行的测试文件,该文件仅告诉我我没有产生正确的输出。 我实际上看不到输出来找出问题所在
我是指针的新手,所以我希望这只是我的简单错误。 我的程序哪里出问题了?
fgets(char * restrict str, int size, FILE * restrict stream)
写入到缓冲器str
...但你不必在一个缓冲str
。 什么是str
? 这只是一个指针。 它指的是什么? 垃圾,因为您尚未将其初始化为某种东西。 因此它可能会起作用,也可能不会起作用( 编辑:我的意思是,您应该指望它不起作用,如果确实起作用,请对此感到惊讶,谢谢评论员! )。
您可以通过先分配一些内存来解决此问题:
char *str = malloc(LINE_MAX_CHARS);
// do your stuff
free(str);
str = NULL;
甚至静态分配:
char str[LINE_MAX_CHARS];
无论如何,这是一个问题。 您说没有输出,但是可以肯定的fprintf(stderr, "")
至少可以使用fprintf(stderr, "")
添加一些调试语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.