-2

I am creating a program that reads an input file of text only and creates a vector of the words in that input file. The program I have now only prompts the user for the input file name and then stops running after that. My text file has only 3 words in it for a test, but by the end of the program I hope to be able to read large text files such as stories.
My code:

#include<string>
#include<iostream>
#include<vector>
#include<fstream> 


using namespace std;


int main(){

 string filename;  //name of text file
 string wordsFromFile;  //the words gathered from the text file

 cout << "Please enter the name of your text file" << endl;
 cin >> filename;

 ifstream fin(filename.c_str());

 fin >> wordsFromFile;

 while(fin >> wordsFromFile)
 {
   fin >> wordsFromFile;
   vector<string>word;
   for(int i=0; i<=word.size(); i++) {
      word.push_back(wordsFromFile);
      cout << word[i];}
   }

   fin.close();
   return 0; 
}
David Nehme
  • 21,379
  • 8
  • 78
  • 117
  • 1
    Have you tried tracing it? What is your actual question? – JTeagle Mar 12 '12 at 17:52
  • 2
    Your loop is **way** to complicated. Instead, say `std::vector words((std::istream_iterator(fin)), std::istream_iterator());` and be done with it. – Kerrek SB Mar 12 '12 at 17:57
  • 1
    Your code doesn't make sense. You're reading a word, then throwing it away, then reading another word, throwing it away, then reading another word and adding it to a vector in an overly complicated way. Please consider starting with an [introductory book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Philipp Mar 12 '12 at 20:06
  • i do have an introductory book. the scope of what i am trying to do in this program is not covered in the book, though. – Scott Clevenger Mar 12 '12 at 20:32

1 Answers1

0

Concerning your actual question

The program I have now only prompts the user for the input file name and then stops running after that.

Since you are not doing any checks if the file exist or not it doesn't help you to know what happen. Is it possible that the file is not located in the correct folder? You don't seem to use any path before the file name, maybe because you are giving the full path on the prompt?

i do have an introductory book. the scope of what i am trying to do in this program is not covered in the book, though

It is usually rare to find a book about what you are doing. However, if you want to learn more about C++ I would recommend C++ Primer Plus, which is a very good book.


Concerning you loop, I would recommend to fill your list on a line per line basis especially if you are planning to load Stories (e.g. couple of megs for a single story).

ForceMagic
  • 6,230
  • 12
  • 66
  • 88