2014-03-04 36 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}}'初始化你的单词二维数组。现在它充满了一堆不确定的数据。或者限制你的高端到你实际添加的字数(即'我 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祝你好运! –