Search code examples
c++arraysfstream

Accessing data in a text file


How could I access a text file and go through word by word. I understand how to open the file but just not how to pull out each word one by one. I think it has something to do with arrays?


Solution

  • Simply:

    #include <fstream>
    #include <iostream>
    
    int main()
    {
      std::fstream file("table1.txt");
    
      std::string word;
      while (file >> word)
        {
          // do whatever you want, e.g. print:
          std::cout << word << std::endl;
        }
    
      file.close();
    
      return 0;
    }
    

    word variable will contain every single word from a text file (words should be separated by space in your file).