Merni
Merni

Reputation: 2912

reading row from text file into two vectors c++

I am trying to read the two words "kelly 1000" in the text file "players", into vectors players and balances respectively. Don't know why it's not working?

string name = "kelly";
int main()
{
    int num =0;
vector<string> players;
vector<int> balances;
ifstream input_file("players.txt");
while(!input_file.eof())
{
    input_file >> players[num];
    input_file >> balances[num];
    num++;
}
for(size_t i = 0; i=players.size(); i++)
{
    if(name==players[i])
        cout << "Welcome " << name << ", your current balance is " << balances[i] <<          "$." << endl;
    else 
        break;
}

Upvotes: 0

Views: 2573

Answers (2)

MoBaShiR
MoBaShiR

Reputation: 440

//Hope this is something you want dear.Enjoy
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;

string name = "kelly";
int main()
{
    int num =0;
    string tempname;
    int tempbalance;
    vector<string> players;
    vector<int> balances;
    ifstream input_file("players.txt");
    while(!input_file.eof())
    {   input_file>>tempname;
      input_file>>tempbalance;

      players.push_back(tempname);
        balances.push_back(tempbalance);

    }
    for(size_t i = 0; i<players.size(); i++)
    {
        if(name==players.at(i))
            cout<< "Welcome " << name << ", your current balance is " << balances.at(i)<<          "$." << endl;

    }
    return 0;
}

Upvotes: 3

jrok
jrok

Reputation: 55415

With operator[] you can only access existing elements. Going out of bounds invokes undefined behaviour. Your vectors are empty and you need to use push_back method to add elements to them.

Second problem is while (!file.eof()) anti-pattern. It'll typicaly loop one to many times because the read of last record doesn't neccesarily trigger eof. When reading from streams, always check whether input succeeded before you make use of values read. That's typicaly done by using operator>> inside loop condition.

string temp_s;
int temp_i;

while (input_file >> temp_s >> temp_i) {
    players.push_back(temp_s);
    balances.push_back(temp_i);
}

This way the loop stops if operator>> fails.

Upvotes: 4

Related Questions