【发布时间】:2014-04-05 08:33:33
【问题描述】:
#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;
}
到目前为止,这是我的代码,我的所有字符都应该适合数组,并且循环看起来在逻辑上是合理的。我不明白为什么我的程序可以编译但不能正确运行。我猜测它可能与二维数组以及我选择用于 strcmp 和 strcpy 的语法有关。但是我尝试用 words[h][0] 代替 words[h] ,但这也不起作用。我有点不知所措,请帮忙!
【问题讨论】:
-
您可以尝试使用
char words[100][16] = {{0}};初始化您的words 2D 数组。现在它充满了一堆不确定的数据。或者将您的高端词限制为您实际添加的字数(即i<h)
标签: c++ arrays strtok strcmp strcpy