ThomasMcDonald
ThomasMcDonald

Reputation: 323

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? This char array will eventually be used to input the current word into a hash table.

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

Upvotes: 0

Views: 2345

Answers (1)

user4581301
user4581301

Reputation: 33932

Don't use a char array unless you absolutely have to. Read them into strings, and toss the strings into your hashtable. If you don't have a hashtable, may I recommend 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;
}

Upvotes: 2

Related Questions