2014-03-04 2 views
0
#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 배열 프로그램이 컴파일되지만 작동하지 않습니다.

당신이이 모든
+0

'char words [100] [16] = {{0}};'을 사용하여 단어 2D 배열을 초기화 해보십시오. 지금은 수많은 불확정 데이터로 가득 차 있습니다. 또는 실제로 추가 한 단어의 수 (예 :'i WhozCraig

답변

0

먼저 배열

char words[100][16] = {}; 

for (i = 0; i < 100; i++) 
{ 
    if (strcmp(token, words[i]) == 0) 
    { 
     unique = false; 
     break; 
    } 
} 

for (i = 0; i < h; i++) 
{ 
    if (strcmp(token, words[i]) == 0) 
    { 
     unique = false; 
     break; 
    } 
} 

이 코드를 변경해야이 루프를 제로 초기화

while (token != NULL) 
{ 
    token = strtok(NULL, " ."); 
    // ... 

내가 그것을 프로그램 충돌의 주요 원인이라고 생각

while ((token = strtok(NULL, " .")) != NULL) 
{ 
    // ... 

대체되어야한다.

또한 파일의 고유 한 단어가 배열의 크기보다 많은지와 토큰의 크기가 배열의 두 번째 크기보다 큰지 확인하지 않습니다.

+0

고맙습니다. 아직 프로그램의 나머지 부분을 완료하지는 못했지만 그것에 도달 할 것입니다. – ryye

+0

@ user3377155 행운을 빌어 요! –

관련 문제