简体   繁体   中英

Cleaning up this code [FILE INPUT]

I have to read from a file that has lines like this:

255 0 0 15 x l Red Yellow,Gray,Blue,Green

Let's say I want to read the first 5 elements of this line (space delimited). I'm currently doing it like this:

std::string line;
while(file.good()) {
    getline(worldfile, line);
    unsigned space = line.find(" ");
    unsigned r = atoi(line.substr(0, space).c_str());
    line = line.substr(space + 1);
    space = line.find(" ");
    unsigned g = atoi(line.substr(0, space).c_str());
    line = line.substr(space + 1);
    space = line.find(" ");
    unsigned b = atoi(line.substr(0, space).c_str());
    line = line.substr(space + 1);
    space = line.find(" ");
    unsigned gold = atoi(line.substr(0, space).c_str());
    line = line.substr(space + 1);
    space = line.find(" ");
    char resource = line.substr(0, space).c_str()[0];
    // do something with these values
}

I don't like the looks of this code. While it works perfectly fine for my files, I don't like that it's just line after line of code. This makes it really hard to read. I'm also planning on releasing my code (it's for a game) as open source when it's done, but I'm ashamed of releasing code like this.

How can I clean this up?

Something like this should work to read them all:

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

using namespace std;

int main ()
{
   fstream file;
    file.open("file.txt",ios::in);
    unsigned r,g,b,gold;
    char i,f;
    string line;
    while(file >> r >> g >> b >> gold >> i >> f)
    {
        getline(file,line);
        cout << r << " " << g << " "<< b << " "<< gold << " "<< i << " "<< f << endl;
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM