gpt4 book ai didi

c++ - 从文件中使用 C++ 中的分词器?

转载 作者:太空宇宙 更新时间:2023-11-04 11:55:29 25 4
gpt4 key购买 nike

我正在做一项作业,要求我从一个文件中读入几行文本,最后使用 qsort 按字母顺序对使用的单词进行排序,并显示每个单词被使用的次数。我意识到我必须在从文件中读入字符串时对其进行标记化。唯一的问题是,在您执行此操作后,单个标记会消失,因此我必须将它们添加到列表中。我不擅长解释,所以这是我的代码:

#include<iostream>
#include<string>
#include<algorithm>
#include<stdlib.h>
#include<fstream>
using namespace std;

int compare(const void* , const void*);
const int SIZE = 1000;
const int WORD_SIZE = 256;
void main()
{
cout << "This program is designed to alphabetize words entered from a file." << endl;
cout << "It will then display this list with the number of times " << endl;
cout << "that each word was entered." << endl;
cout << endl;
char *words[SIZE];//[WORD_SIZE];
char temp[100];
char *tokenPtr, *nullPtr= NULL;
char *list[SIZE];
string word;
int i = 0, b = 0;
ifstream from_file;
from_file.open("prob1.txt.txt");
if (!from_file)
{
cout << "Cannot open file - prob1.txt";
exit(1); //exits program
}

while (!from_file.eof())
{
from_file.getline(temp, 99);
tokenPtr = strtok(temp, " ");
while (tokenPtr != NULL)
{
cout << tokenPtr << '\n';
list[b] = tokenPtr;
b++;
tokenPtr = strtok(nullPtr, " ");
}
word = temp;
transform(word.begin(), word.end(), word.begin(), ::tolower);
words[i] = list[i];
i++;
}
from_file.close();
qsort(words, i, WORD_SIZE, compare);
int currentcount = 1 ;
int k;
for( int s = 0; s < i; s++ )
{
for( k = 1; k <= s; k++)
{
if( words[s] == words[k] )
{
currentcount++;
}
currentcount = 1;
words[k] = "";
}
cout << words[s] << " is listed: " << currentcount << " times." << endl;
words[s] = "";

}
}
int compare(const void* p1, const void *p2)
{
char char1, char2;

char1 = *(char *)p1; // cast from pointer to void
char2 = *(char *)p2; // to pointer to int

if(char1 < char2)
return -1;
else
if (char1 == char2)
return 0;
else
return 1;
}

唯一缺少的是比较功能,但程序运行良好,直到 qsort 崩溃,但它没有告诉我原因。任何人都可以分享一些见解/帮助我解决这个问题吗?

同样,这是一项作业。 (有人告诉我我需要指定这个?)

最佳答案

数组 words 是指向 char 的指针数组:

char*   words[SIZE];   // SIZE elements of type `char*`

所以第三个参数WIDTH应该是指向char的指针的宽度。

qsort(words, i, sizeof(char*), compare);

此外,您的比较实现未按预期工作。
您正在将指针传递给比较。但它们是元素的指针。您需要取消引用指针以获取值:

int compare(const void* p1, const void *p2)
{
char const* x = *(char**)p1;
char const* y = *(char**)p2;

这不比较字符串:

if( words[s] == words[k] )

这只是比较两个指针。要比较它们指向的字符串,请使用 strcmp()

if( strcmp(words[s], words[k]) == 0)

这应该可以阻止崩溃,但是我们可以对这段代码做更多的改进:
一旦你让它工作,你应该把它贴在这里 https://codereview.stackexchange.com/进行审查。

关于c++ - 从文件中使用 C++ 中的分词器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16312234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com