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