清理此代码[FILE INPUT]

时间:2013-04-15 21:51:01

标签: c++ oop file-io

我必须从包含这样的行的文件中读取:

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

假设我想读取此行的前5个元素(空格分隔)。我现在这样做:

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
}

我不喜欢这段代码的外观。虽然它对我的文件完全正常,但我不喜欢它只是一行一行的代码。这使得它很难阅读。 我还计划在完成后将我的代码(它是游戏)发布为开源代码,但我对发布这样的代码感到羞耻。

我该如何清理它?

1 个答案:

答案 0 :(得分:3)

这样的东西应该可以全部阅读:

#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;
}
相关问题