c++ - 将文件中的每个单词读入 C++ 中的 char 数组

标签 c++ arrays

使用 ifstream() 读取文件然后将每个单词存储在 char 数组中的正确方法是什么?该字符数组最终将用于将当前单词输入到哈希表中。

我的代码:

int main()
{
  int array_size = 4096; 
    char * filecontents = new char[array_size]; 
    char * word = new char[16];
    int position = 0; 
    ifstream fin("Dict.txt"); 

  if(fin.is_open())
    {

    cout << "File Opened successfully" << endl;
        while(!fin.eof() && position < array_size)
        {
            fin.get(filecontents[position]); 
            position++;
        }
        filecontents[position-1] = '\0';

        for(int i = 0; filecontents[i] != '\0'; i++)
        {
            word[i] = filecontents[i];
            //insert into hash table
            word[i] = ' ';

        }
        cout << endl;
    }
    else 
    {
        cout << "File could not be opened." << endl;
    }
    system("pause");
    return 0;
}

最佳答案

除非万不得已,否则不要使用字符数组。将它们读入字符串,然后将字符串放入哈希表中。如果你没有哈希表,我可以推荐std::set吗? ?可能正好符合您的需要。

阅读资料。试一试:

int main()
{
    ifstream fin("Dict.txt");
    set<string> dict;  // using set as a hashtable place holder.

    if (fin.is_open())
    {
        cout << "File Opened successfully" << endl;
        string word;
        while (getline(fin, word, '\0'))
        {  /* getline normally gets lines until the file can't be read, 
                but you can swap looking for EOL with pretty much anything 
                else. Null in this case because OP was looking for null */
           //insert into hash table
            dict.insert(word); //putting word into set
        }
        cout << endl;
    }
    else
    {
        cout << "File could not be opened." << endl;
    }
    system("pause"); // recommend something like cin >> some_junk_variable
    return 0;
}

关于c++ - 将文件中的每个单词读入 C++ 中的 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30135403/

相关文章:

JavaScript:如何生成随机字母表,其中某些单词随机隐藏?

c# - System.Array 不包含 'Any' 的定义 - C#

c++ - 在变量地址上调用 delete

c++ - 使用 'std::algorithm' 无显式循环迭代自定义对的 vector

c++ - 如何检索具有完整路径的文件名以将数据写入其中

javascript - 如何解析 JSONArray 并在 Javascript 中进行转换

c++ - 如何使用 POCO 库将更改写入 ".ini"文件?

c++ - 如何对非常大的数进行算术运算

c++ - 错误: cannot convert ‘std::string {aka std::basic_string<char>}’ to ‘char*’ in initialization

c++ - 如何让一个整数对数组按两个整数排序,同时仍然在 C 中关联它们?