【问题标题】:C++ strtok and 2d arrays. Program compiles but crashesC++ strtok 和二维数组。程序编译但崩溃
【发布时间】: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&lt;h

标签: c++ arrays strtok strcmp strcpy


【解决方案1】:

首先你必须对数组进行零初始化

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;
    }
}

这段代码sn-p

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

必须替换

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

我认为这是程序崩溃的主要原因。

您也不会检查文件中的唯一词是否比数组的大小更多,以及令牌的大小是否大于数组的第二个大小。

【讨论】:

  • 谢谢,修复了崩溃问题。我还没有完成程序的其余部分,但我会完成的。
  • @user3377155 祝你好运!
猜你喜欢
  • 2015-01-28
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多