파일에서 여러 줄의 텍스트를 읽어야하는 과제를 진행하고 있으며 qsort를 사용하여 사전 순으로 사용 된 단어를 정렬하고 각 단어가 몇 번 사용되었는지 계산합니다. 파일에서 읽어 들일 때 문자열을 토큰 화해야한다는 것을 알게되었습니다. 유일한 문제는 개별 토큰 종류가 사라진 후에 사라 지므로 목록에 추가해야한다는 것입니다. 나는 설명에 나쁜, 그래서 여기 내 코드입니다 : 유일한 것은이 누락C++에서 파일의 토큰 화 도구 사용?
#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가, 때까지 잘 작동하지만 그것은 말하지 않는다 왜. 아무도 통찰력을 잃을 수 있습니까 /이 문제를 해결할 수 있습니까?
다시 한 번 이것은 할당입니다.
char* words[SIZE]; // SIZE elements of type `char*`
그래서 세 번째 매개 변수
WIDTH
이는 char에 대한 포인터의 폭과 같아야합니다
'while (from_file.getline (temp, 99))'을 읽는 줄에 씁니다. – Nawaz
코드에 많은 문제점이 있습니다.'qsort''strtok'을 지뢰로 가득 차 있기 때문에 사용하지 말 것을 제안합니다. 'std :: string','std :: sort'를 사용하고, 그래서 문자열 분리 함수를 찾으십시오. – yngccc
어디에서 비교 함수를 작성 했습니까? 나는 그것의 정의를 볼 수 있지만 그것을 구현하는 코드는 없다. – Jay