#include <iostream>
#using namespace std;
#include <cstring>
#include <fstream>
int main(int argc, char *argv[])
{
ifstream file;
// check for valid user input
if (argc != 2)
{
cout << "Please enter the file name." << endl;
return 0;
}
else
{
file.open (argv[1]);
// check if file is valid
if (file == 0)
{
cout << "File is not valid." << endl;
return 0;
}
}
char words[100][16]; // 2d array for unique words
char line[100]; // c-string to hold a line
char *token = NULL;
int h=0; // variable for counting array index
int i, j; // counter variables
while (file.getline (line, 100, '\n'))
{
bool unique = true; // boolian to test for unique words
cout << line << endl; // echo print the line
token = strtok(line, " ."); // 1st token
if (token == NULL) // check if 1st token exists
{
break;
}
// loop to check if token is unique
for (i = 0; i < 100; i++)
{
if (strcmp(token, words[i]) == 0)
{
unique = false;
break;
}
}
if (unique == true)
{
strcpy(words[h], token);
h++;
}
unique = false;
// another loop to continue strtok and check for unique words
while (token != NULL)
{
token = strtok(NULL, " .");
for (i = 0; i < 100; i++)
{
if (strcmp(token, words[i]) == 0)
{
unique = false;
break;
}
}
if (unique == true)
{
strcpy(words[h], token);
h++;
}
}
}
return 0;
}
이것은 지금까지 작성한 코드입니다. 모든 문자가 배열에 맞아야하고 루프가 논리적으로 소리가 나는 것처럼 보입니다. 내 프로그램이 컴파일되지만 올바르게 실행되지 않는 이유를 모르겠습니다. 나는 2 차원 배열과 strcmp와 strcpy에 사용하기 위해 선택한 문법과 관련이있을 것이라고 추측하고있다. 하지만 단어 [h] [0] 대신 단어 [h]를 넣으려고했는데 그 중 하나도 작동하지 않습니다. 나는 일종의 완전한 손실 여기, 제발 도와주세요!C++ strtok 및 2d 배열 프로그램이 컴파일되지만 작동하지 않습니다.
당신이이 모든
'char words [100] [16] = {{0}};'을 사용하여 단어 2D 배열을 초기화 해보십시오. 지금은 수많은 불확정 데이터로 가득 차 있습니다. 또는 실제로 추가 한 단어의 수 (예 :'i
WhozCraig