C++ Reading Data in a File I'm not sure if I should ask here. The program worked it's just that I'm not satisfied how I implemented it because I used two while loop to read a specific data and I have no idea what am I doing. How can I make it more efficient and instead of using two while loop?

spritesheet.txt



int main() {

fstream file("spritesheet.txt");

int x, y, width, height;
string num1, num2;
string line;
string data;

if (file.is_open())
{
    while (getline(file, line))
    {
        if (line == "enemy")
        {
            while (file &gt;&gt; data &gt;&gt; num1 &gt;&gt; num2)
            {
                if (data == "xy:")
                {
                    x = std::stoi(num1);
                    y = std::stoi(num2);
                    cout &lt;&lt; "x: " &lt;&lt; x &lt;&lt; endl &lt;&lt; "y: " &lt;&lt; y &lt;&lt; endl;
                }
                if (data == "size:")
                {
                    width = std::stoi(num1);
                    height = std::stoi(num2);
                    cout &lt;&lt; "width: " &lt;&lt; width &lt;&lt; endl &lt;&lt; "height: " &lt;&lt; height &lt;&lt; endl;
                }
            }
            file.close();
            break;
        }
    }
}
system("pause");


}
You could add state to the reader: e.g. have a std::string variable target outside of the loop, read the lines in a while loop and...

while (getline(file, line)) {
  if (line=="enemy" || line=="player") {
    target=line; // remember where to put things
  }
  else {
    const std::string::size_type p=line.find(":");
    if (p!=std::string::npos) {
      assert(!target.empty());
      const std::string tag=line.substr(0, p);
      const std::string val=line.substr(p+1);

      // parse val (maybe with istringstream),
      // then put values into appropriate destination,
      // by using target and tag
    }
  }
}