文件时的几个星期到现在,我一直在开发使命的Xbox游戏呼叫随机类生成:现代战争3在这个游戏中,不同的武器有不同的水平,随着你更多地使用武器。我储存武器及其在文本文件中的水平,这在不同的行中的数据存储与格式奇怪的结果编辑在C++
weapon-weapon_level
所以M4A1与武器级8会是什么样子:
m4a1-8
(该武器都是小写字母,没有标点或空格)。
我已经写了创建文件和读取文件的方法,但我想一个方法来编辑文件,所以用户输入他们想要改变,那么新的水平,其水平的武器。这是我到目前为止:(文件名为“weaponlevels.txt”)
void WeaponLevelFile::editFile()
{
string line;
string weapon;
string weaponent;
string weaponlevel;
string temp;
cout<<"Please enter the weapon whose level you wish to change. Enter the name in lowercase, with "<<endl;
cout<<"no spaces or punctuation except full stops. E.g. SCAR-L becomes scarl and Barrett .50cal "<<endl;
cout<<"becomes barrett.50cal."<<endl;
cin>>weaponent;
cout<<"Please enter the new weapon level."<<endl;
cin>>temp;
ifstream infile("weaponlevels.txt");
ofstream outfile("weaponlevels.txt");
while (getline(infile, line))
{
istringstream ss(line);
getline(ss,weapon,'-');
if (weapon == weaponent)
{
ss>>weaponlevel;
weaponlevel=temp;
outfile<<weaponlevel<<endl;
infile.close();
outfile.close();
}
}
}
但这种方法不起作用;它所做的只是擦除文件(所以文件是空白的)。它为什么这样做,什么是更好的方法?
编辑: @ stardust_的答案工作的最好的,但仍然没有完全做到这一点。这里是代码:
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main()
{
string temp;
string line;
string weapon;
string weaponent;
string weaponlevel;
cout<<"enter weapon"<<endl;
cin>>weaponent;
cout<<"enter level"<<endl;
cin>>temp;
ifstream infile("weaponlevels.txt");
std::string in_str((std::istreambuf_iterator<char>(infile)),
std::istreambuf_iterator<char>());
infile.close();
stringstream infile_ss(in_str);
while (getline(infile_ss, line))
{
istringstream ss(line);
getline(ss,weapon,'-');
if (weapon == weaponent)
{
ss>>weaponlevel;
weaponlevel=temp;
infile_ss<<weaponlevel<<endl;
}
}
ofstream outfile("weaponlevels.txt");
outfile << infile_ss.str();
outfile.close();
}
它修改“weaponlevels.txt”的正确部分,但并没有完全做到这一点。如果我进入m4a1
作为武器,7
为武器的水平,而不是成为m4a1-7
就变成:
7
a1-3
使用另一个文件的ofstream的。您正在阅读和写入同一个文件。另外,在使用之前请检查文件是否已成功打开。 'ofstream outfile(“weaponlevels.txt”); ' – 2013-04-08 13:18:01
@stardust_我想要读/写同一个文件。在我的问题,它说我想**编辑**它 – imulsion 2013-04-08 13:18:52
,如果你打开一个文件'ofstream'默认模式'的ios_base :: out'如果你想它清除文件,追加使用'的ios_base :: app'。如果你想在文件中间的某个地方改变一些数据,并且它的大小不同,那么你想要替换的部分或者需要在内存中重建你的文件并用你的'ostream'或者你需要创建的文件立即写回来一个新文件,您在删除旧文件后重新命名。 – 2013-04-08 13:25:20