Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Problem with reading a int (http://www.go4expert.com/forums/reading-int-t15784/)

Renzokusen 10Jan2009 07:40

Problem with reading a int
 
Ok I am simply trying to reduce the size of my item data base for this console rpg I am making. I wish to put all the creature names & hp & atk etc in a file then use the ifstream to retrieve this data when I need and place the values in certain variables. I am able to retrieve names, but when it comes to the int's I have problems of conversion.

Here is my test code.

Code:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    ifstream in("happy.txt");
    string line;
    string key = "MONSTER_NAME";
    string two = "Weapon_Name";
    string weaponDamage = "Weapon_Damage";
    string dataSought;
    string weaponName;
    int attack = 0;


  // Read the label "attack" followed by the value
  //_file >> label >> attack;

    while( getline(in, line) )
    {
        //weaponDamage >> attack;
       
        if( key == line.substr(0, key.length()) )
        {
            dataSought = line.substr( key.length()+1 );
            cout << dataSought;
        }
        if( two == line.substr(0, two.length()) )
        {
            weaponName = line.substr( two.length());
            cout << weaponName;           
        }
        if( weaponDamage == line.substr(0, weaponDamage.length()))
        {
                        in >> attack;
             
        }
        }
   
      cout << attack;
    cout << endl;
    system("pause");
}

The test txt file

Code:

xxx ... ... ...
xxz ... ... ...
MONSTER_NAME King Fish Crab
Weapon_Name Zanbato
Weapon_Damage 100
xzz ... ... ...

Now I can display the name of the monster, weapon name, but the attack variable remains unchanged.

Anybody know how to fix this?

sharmila 11Jan2009 18:20

Re: Problem with reading a int
 
getline() will return including the integer value... so I think when we say in>>attack then it will try to read the next value which will be in the next line.. but we need int value which is already read from the file and is in the line...
so instead of taking from file better to take from line variable...

if( weaponDamage == line.substr(0, weaponDamage.length()))
{
//in >> attack;
/* to get the position of space.. or we can do pos = strlen(weaponDamage); */
int pos = line.find(" ");
/* as pos will point to starting position of " " increamenting that to get the next position so that we will get the number.. */
pos++;
attack = atoi(line.substr(pos)); // converting string to integer

}
I think we can we try like this..


All times are GMT +5.5. The time now is 03:49.