嘿,可能有一个文本文件,其内容为:
Weapon Name: Katana
Damage: 20
Weight: 6
是否可以将这些信息分配给武器类别的成员变量?
这样,当我在主目录中调用getWeaponName时,我将获得Katana吗?
我环顾谷歌,我可以得到整个文本文件输入,但未分配给任何变量。
我到目前为止的代码是:
Weapons :: Weapons()
{
this->weaponName = "";
this->damage = 0;
this->weight = 0;
}
Weapons :: Weapons(string weaponName,int damage,int weight)
{
this->weaponName = weaponName;
this->damage = damage;
this->weight = weight;
}
void Weapons :: getWeapon()
{
ifstream myfile ("Weapons\\Katana.txt");
string line;
if (myfile.is_open())
{
while (myfile.good())
{
getline (myfile,weaponName,'\t');//This line gets the entire text file.
//getline (myfile,damage,'\t');
//getline (myfile,weight,'\t');
//myfile >> weaponName;
//myfile >> damage;
//myfile >> weight;
cout << weaponName<< "\n";
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
}
提前致谢。
最佳答案
更改
getline (myfile, weaponName, '\t');
至
getline (myfile, weaponName);
您的版本正在执行的操作是告诉
getline
抓住文件中的所有内容,最多包含一个制表符,而我猜您没有任何制表符。我推荐的版本(未指定分隔符)将使字符换行。因此,应在Weapon Name: Katana
中读取。然后,您仍然需要提取“ Katana”。假设您的输入文件格式非常固定,则只需执行以下操作即可
weaponName = weaponName.substr(weaponName.find_first_of(':') + 2);
该子字符串将从':'之后的位置2开始。
编辑
使用
weaponName
不适用于您的getline语句。 weaponName
是一个字符串,但是到那时,您只是在寻找一行。您已经在getWeapon()
中放置了适当的变量。我们只需要使用它们:void Weapons :: getWeapon()
{
ifstream myfile ("Weapons\\Katana.txt");
string line;
string number;
if (myfile.is_open())
{
while (myfile.good())
{
getline (myfile,line);
weaponName = line.substr(line.find_first_of(':') + 2);
getline (myfile,line);
number = line.substr(line.find_first_of(':') + 2);
damage = atoi(number.c_str());
getline (myfile,line);
number = line.substr(line.find_first_of(':') + 2);
weight = atoi(number.c_str());
cout << weaponName<< "\n";
}
myfile.close();
}
else
{
cout << "Unable to open file";
}
}
注意:您需要
#include <stdlib.h>
才能使atoi
工作。老实说,这仍然不是很可靠。其他人为您提供了更好的解决方案,例如查看输入以查看数据是什么,以及读取和存储所有数据,但这应该向您展示了最基本的知识。