views:

482

answers:

4

I would like to read a text file and input its contents into an array. Then I would like to show the contents of the array in the command line.

My idea is to open the file using:

inFile.open("pigData.txt")

And then to get the contents of the file using:

inFile >> myarray [size]

And then show the contents using a for loop.

My problem is that the file I am trying to read contain words and I don't know how to get a whole word as an element in the array. Also, let's say that the words are divided by spaces, thus:

hello goodbye

Could be found on the file. I would like to read the whole line "hello goodbye" into an element of a parallel array. How can I do that?

+4  A: 

Should be pretty straightforward.

std::vector<std::string> file_contents;
std::string line;
while ( std::getline(inFile,line) )
    file_contents.push_back(line);

std::vector<std::string>::iterator it = file_contents.begin();
for(; it!=file_contents.end() ; ++it)
    std::cout << *it << "\n";

Edit:

Your comment about having "hello goodbye" as element zero and element one is slightly confusing to me. The above code snip will read each line of the file and store that as an individual entry in the array 'file_contents'. If you want to read it and split it on spaces that is slightly different.

DeusAduro
Thank you for the help!
jualin
+3  A: 
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

int main()
{
    // This will store each word (separated by a space)    
    vector<string> words;
    // Temporary variable
    string buff;

    // Reads the data
    fstream inFile("words.txt");
    while(!inFile.eof())
    {
     inFile>>buff;
     words.push_back(buff);
    }
    inFile.close();

    // Display
    for(size_t i=0;i<words.size();++i) cout<<words[i]<<" ";
    return 0;
}
Jacob
+1  A: 
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

int main ()
{
    vector<string> fileLines;
    string line;
    ifstream inFile("pigData.txt");
    if ( inFile.is_open() ) {
        while ( !inFile.eof() ) {
            getline(inFile, line);
            fileLines.push_back(line);
        }
        inFile.close();
    } else {
        cerr << "Error opening file" << endl;
        exit(1);
    }

    for (int i=0; i<fileLines.size(); ++i) {
        cout << fileLines[i] << "\n";
    }
    cout << endl;

    return 0;
}
merv
+2  A: 

For context, you could have provided a link to your previous question, about storing two lists of words in different languages. There I provided an example of reading the contents of a text file into an array:

const int MaxWords = 100;
std::string piglatin[MaxWords];
int numWords = 0;
std::ifstream input("piglatin.txt");
std::string line;
while (std::getline(input, line) && numWords < MaxWords) {
  piglatin[numWords] = line;
  ++numWords;
}
if (numWords == MaxWords) {
  std::cerr << "Too many words" << std::endl;
}

You can't have one parallel array. For something to be parallel, there must be at least two. For parallel arrays of words, you could use a declarations like this:

std::string piglatin[MaxWords];
std::string english[MaxWords];

Then you have two options for filling the arrays from the file:

  1. Read an entire line, and the split the line into two words based on where the first space is:

    while (std::getline(input, line) && numWords < MaxWords) {
      std::string::size_type space = line.find(' ');
      if (space == std::string::npos)
        std::cerr << "Only one word" << std::endl;
      piglatin[numWords] = line.substr(0, space);
      english[numWords] = line.substr(space + 1);
      ++numWords;
    }
    
  2. Read one word at a time, and assume that each line has exactly two words on it. The >> operator will read a word at a time automatically. (If each line doesn't have exactly two words, then you'll have problems. Try it out to see how things go wrong. Really. Getting experience with a bug when you know what the cause is will help you in the future when you don't know what the cause is.)

    while (input && numWords < MaxWords) {
      input >> piglatin[numWords];
      input >> english[numWords];
      ++numWords;
    }
    

Now, if you really one one array with two elements, then you need to define another data structure because an array can only have one "thing" in each element. Define something that can hold two strings at once:

struct word_pair {
  std::string piglatin;
  std::string english;
};

Then you'll have just one array:

word_pair words[MaxWords];

You can fill it like this:

while (std::getline(input, line) && numWords < MaxWords) {
  std::string::size_type space = line.find(' ');
  if (space == std::string::npos)
    std::cerr << "Only one word" << std::endl;
  words[numWords].piglatin = line.substr(0, space);
  words[numWords].english = line.substr(space + 1);
  ++numWords;
}

Notice how the code indexes into the words array to find the next word_pair object, and then it uses the . operator to get to the piglatin or english field as necessary.

Rob Kennedy
Thank you very much for the explanation. I am sorry for not posting a link to the last question. You have truly made it clearer now, I think that I will try option number 2 since each line has exactly 2 words.
jualin