2015-05-09 2 views
0

Каков правильный способ чтения в файле с использованием ifstream(), а затем хранения каждого слова в массиве символов? Этот массив символов в конечном итоге будет использоваться для ввода текущего слова в хеш-таблицу.Чтение каждого слова из файла в массив символов в C++

Мой код:

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

Правильный путь будет читать файл в 'станд :: VECTOR' из' станд :: strings', как это C++ – NathanOliver

+0

Вы ** всегда ** нужно проверить * * после ** чтения, если операция была успешной: перед попыткой прочитать поток не будет знать, что вы собираетесь попробовать, и нет способа определить, будет ли эта попытка успешной. –

ответ

2

Не используйте массив символов, если вы абсолютно не должны. Прочитайте их в строках и бросьте струны в свою хэш-таблицу. Если у вас нет хеш-таблицы, могу ли я рекомендовать 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; 
} 
Смежные вопросы