因此,我的数据结构老师给了我一个作业:一个C代码,该代码遍历文本并返回一个链接列表,其中包含单词和在文本中找到单词的次数(他没有说出分隔单词的细节)只能用空格隔开。
到目前为止,我已经设法在C语言中创建了一个运行良好的链接列表:插入insere()
,打印机imprime()
,按单词buscaPorOcorrenciaDePalavra()
搜索和最后一个单词getter { {1}}在main中调用时都具有全部功能。但是,当我尝试从终端获取输入时,输出全部混乱了。有时单词会被切成两半,有时只会捕获换行符,找不到适当的输入处理。
我不知道它是否会影响代码,但是我确实知道您不应该在feof()上循环,但这是我的老师要求我这样做的方式。
代码:
buscaFinalFila()
输入示例:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct _item {
int x; char* palavra;
struct _item *prox;
} item;
item* buscaFinalFila(item* cabeca){
item* searcher;
searcher = cabeca;
while (searcher->prox != NULL){
searcher = searcher->prox;
} return searcher;
}
void insere(item* cabeca,int x, char* palavra){
item* novo; item* pt;
novo = malloc(sizeof(item));
novo->x = x;
novo->palavra = palavra;
pt = buscaFinalFila(cabeca);
if(cabeca == NULL){
novo->prox = NULL;
pt = novo;
} else {
novo->prox = pt->prox;
pt->prox = novo;
}
}
item* buscaPorOcorrenciaDePalavra(item* cabeca,char* chave){
item* searcher;
searcher = cabeca;
while ((searcher->palavra != chave)&&(searcher->prox != NULL)){
searcher = searcher->prox;
} return searcher;
}
void imprime(item* cabeca){
item* searcher;
searcher = cabeca;
while (searcher->prox != NULL){
searcher = searcher->prox;
printf("%s %d\n",searcher->palavra,searcher->x);
}
}
int main(){
char* input;
char* token;
item* cabeca = NULL;
cabeca = malloc(sizeof(item));
while(!feof(stdin)){
input =(char*) malloc (80*sizeof(char));
fgets(input,80,stdin);
token = strtok(input," \n");
while (token != NULL){
insere(cabeca,1,token);
token = strtok(NULL," \n");
}
free(input);
} imprime(cabeca);
return 0;
}
输出示例:This input is for StackOverflow
An this is where stuff gets weird
如何正确输出此输出?而我在哪里犯了错误?