0

我正在尝试将文本文件“players”中的“kelly 1000”这两个词分别读入向量 player 和 balances 中。不知道为什么它不起作用?

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;
}
4

2 回答 2

4

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.

于 2013-08-30T10:46:14.753 回答
3
//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;
}
于 2013-08-30T11:51:44.607 回答