简体   繁体   English

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

[英]Reading each word from a file into a char array in C++

What is the correct way of reading in a file using ifstream() and then storing each word in an a char array? 使用ifstream()读取文件然后将每个单词存储在char数组中的正确方法是什么? This char array will eventually be used to input the current word into a hash table. 该char数组最终将用于将当前单词输入到哈希表中。

My code: 我的代码:

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

Don't use a char array unless you absolutely have to. 除非绝对必要,否则不要使用char数组。 Read them into strings, and toss the strings into your hashtable. 将它们读取为字符串,然后将字符串放入哈希表中。 If you don't have a hashtable, may I recommend std::set ? 如果您没有哈希表,我可以推荐std :: set吗? Probably right in line with what you need. 可能恰好符合您的需求。

Reading stuff. 阅读的东西。 Give this a try: 试试看:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM