我试图在文本文件“players”中读取两个词“kelly 1000”,分别为向量播放器和余额。不知道为什么它不起作用?
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;
}
答案 0 :(得分:4)
使用operator[]
,您只能访问现有元素。走出界限会调用未定义的行为。你的向量是空的,你需要使用push_back
方法向它们添加元素。
第二个问题是while (!file.eof())
反模式。它通常会循环一次到多次,因为读取最后一条记录并不一定会触发eof
。从流中读取时,总是在使用读取的值之前检查输入是否成功。这通常是通过使用operator>>
内部循环条件来完成的。
string temp_s;
int temp_i;
while (input_file >> temp_s >> temp_i) {
players.push_back(temp_s);
balances.push_back(temp_i);
}
这样,如果operator>>
失败,循环就会停止。
答案 1 :(得分: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;
}