For a couple of weeks now, I have been writing a random class generator for the Xbox game Call of Duty: Modern Warfare 3. In this game, weapons have 'levels' which, as the weapon level increases, allow you to attach different items to your weapon, for instance a silencer. Part of what I want my program to do is to store the user's current weapon level for each weapon in a text file with the format:
weapon-weapon_level
I then want my program to ask the user to enter a weapon in string format. The program should then go through the text file, and if it finds the text string as one of the weapons, output the weapon level for that weapon.
I am completely stumped on how to do this, so any help is much appreciated!
You could read the file one line at a time. Then split the line at the delimiter (looks like character '-' in your example) and compare the user input with the value from the file.
You could use a stringstream or string find() and substr() depending on preference. I would use the stringstream method.
Ok, based on your examples, I tried to write a file to do what i wanted. Only it doesn't work. When i enter the weapon it just freezes and I have to terminate it with Ctrl+C. Why is this?
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
usingnamespace std;
int main()
{
string line;
string weapon;
string weaponent;
string weaponlevel;
cout<<"Enter weapon"<<endl;
getline(cin,weaponent);//get entered weapon
ifstream read("weaponlevels.txt");//open file
while(!read.eof())//iterate through file line by line
{
istringstream ss(line);//initialize stringstream object
getline(ss,line,'\n');//get line in file
getline(ss,weapon,'-');//read up to delimiter
if(weapon == weaponent)//if weapon is equal to entered weapon
{
ss>>weaponlevel;//then get weapon level
}
else
{
continue;//otherwise go to next line
}
}
cout<<weaponlevel<<endl;//print weapon level
return 0;
}
You open the file, but never actually read anything from it. By the way, I'd recommend using a different name for the file, since read() is the name of a member function.
Thank you so much for all your help :) I am such a noob at c++ so I apologize for my stupidity and thank you again for your patience. This question would probably have been deleted if i was still on stackoverflow!