1

ファイルから数行のテキストを読み取る必要がある課題に取り組んでおり、最後に 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までは正常に動作しますが、その理由はわかりません。誰でも洞察を得ることができますか、これを修正するのを手伝ってくれますか?

繰り返しますが、これは課題です。(これを指定する必要があると言われましたか?)

4

1 に答える 1