André Foote
André Foote

Reputation: 368

Issue with file reading and vector entries

The purpose of this program is to read a text file and store its contents in 3 separate vectors.

The text file, called "InsultsSource.txt", contains 50 rows of tab-delimited columns of adjectives that looks like this:

happy    sad    angry
tired    mad    hungry

Below is the code I'm using to achieve this. For some reason, the everything works until the 16th line at which point empty spaces are returned. I've checked the text file to see if the format changes around there but it looks fine. I'm just wondering if there's any error in my logic/code that is causing this problem.

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

using namespace std;

int main() {

    ifstream fileIn("InsultsSource.txt");
    vector<string> col1;
    vector<string> col2;
    vector<string> col3;
    string word;

    if (fileIn.fail()) {
        cerr << "Unable to open file" << endl;
    }

    for (int i = 0; i < 50; i++) {
        if (i % 3 == 0) {
            getline(fileIn, word, '\t');
            col1.push_back(word);
        }
        else if (i % 3 == 1) {
            getline(fileIn, word, '\t');
            col2.push_back(word);
        }
        else {
            getline(fileIn, word);
            col3.push_back(word);
        }
    }

    for(int j = 0; j < 50; j++) {
        cout << j+1 << " " << col1[j] << endl;
        //cout << "Thou " << col1[j] << " " << col2[j] << " " << col3[j] << "!" << endl;
    }
    return 0;
}

Upvotes: 0

Views: 41

Answers (3)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Rather use something like

std::string val1, val2; val3;

vector<string> col1;
vector<string> col2;
vector<string> col3;

while(fileIn >> val1 >> val2 >> val3) {
    col1.push_back(val1);
    col2.push_back(val2);
    col3.push_back(val3);
}

Upvotes: 1

Beta
Beta

Reputation: 99084

You are reading in 50 words total, then trying to print 50 words from each column.

Upvotes: 1

Thomas Matthews
Thomas Matthews

Reputation: 57678

Get rid of the for loop, use while instead:

std::string text;
while (std::getline(fileIn, text, '\t'))
{
  col1.push_back(text);
  std::getline(fileIn, text, '\t');
  col2.push_back(text);
  std::getline(fileIn, text);
  col3.push_back(text);
}

This could be a case where you want to model each line with a structure.

struct Record
{
  std::string col1;
  std::string col2;
  std::string col3;
}
std::vector<Record> database;
Record r;
while (std::getline(fileIn, r.col1, '\t')
{
  std::getline(fileIn, r.col2, '\t');
  std::getline(fileIn, r.col3);
  database.push_back(r);
}

Upvotes: 1

Related Questions