【发布时间】:2018-02-07 16:03:55
【问题描述】:
对于重复的问题,我很抱歉,但我对 C 编程非常陌生,无法理解如何在我自己的代码中实现相同顶部的先前答案。
我要从磁盘上的文件或标准输入中读取文本,对单词进行排序,然后向用户显示单词出现的列表(出现次数最多的单词在顶部,然后按降序排列)。
我目前坚持将我的标记化单词存储为一种合适的方式,以便以后能够对它们进行计数和排序。我决定使用结构。
我编写了一个测试文件,在其中使用来自 stdin 的 fgets 为其提供数据。
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char const *argv[])
{
struct words
{
char word[500];
unsigned int count;
};
int size = 500;
char *buffer;
char token;
struct words w;
#ifdef DEBUG
printf("--!DEBUG INFO!-- \n Right before the 4-loop now\n--!DEBUG INFO!--\n");
#endif
for (int i = 0; i < 10; ++i)
{
printf("Please enter word\n");
fgets(buffer, size, stdin);
#ifdef DEBUG
printf("--!DEBUG INFO!-- \n %c\n--!DEBUG INFO!--\n", buffer);
#endif
token = strtok(buffer[i], "\n");
strcpy(w.word[i], token);
#ifdef DEBUG
printf("--!DEBUG INFO!-- \n %c\n--!DEBUG INFO!--\n", w.word[i]);
#endif
}
for (int i = 0; i < 10; ++i)
{
printf("%c\n", w.word[i]);
}
return 0;
}
在编译时,我收到一大堆警告消息,其中大多数都表示类似以下内容:
incompatible pointer to integer conversion assigning to 'char' from
'char *'; dereference with * [-Wint-conversion]
token = strtok(buffer[i], "\n");
该程序确实会编译并运行,直到我给它数据并按回车键。之后,它会因分段错误而崩溃:11 条消息
./tok_struct
--!DEBUG INFO!--
Right before the 4-loop now
--!DEBUG INFO!--
Please enter word
Test
Segmentation fault: 11
我非常感谢能得到任何帮助!
【问题讨论】:
-
把这一切
#ifdef DEBUG废话,学习使用调试器。 -
我很乐意这样做,但该模块基于学习非常基本的方法,即在我的情况下终端和崇高文本。
-
好吧,为了课程,按照你的方式去做,为了找到一份好工作,按照我的方式去做。也就是说,双向进行。
-
@Bathsheba 上三个月在 Eclipse 中编写 Java 之后,我非常热衷于使用调试器,并且将来会这样做。但是,我也确实看到了不这样做以了解后台实际发生的事情的意义。 :)
-
这很奇怪——我一直认为调试器会准确地告诉你后台发生了什么。