c++ - 清理此代码 [文件输入]

标签 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
}

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

我该如何清理它?

最佳答案

像这样的东西应该可以阅读所有内容:

#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;
}

关于c++ - 清理此代码 [文件输入],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16025285/

相关文章:

C++:正确使用 LoadImage 和 SetCursor 函数

c++ - 创建驱动程序时发生错误。设备驱动程序未安装在任何设备上,请使用原始驱动程序(如果提供)

c++ - 为什么这两个重载函数的声明方式不同?

在 R 中并行读取和处理文件

matlab - 使用 MATLAB 从 xml 文件中提取数据

C++ 从程序集输出的角度理解虚拟析构函数如何增加类型的大小

C++ 将结构传递给函数

java - 读取不同行格式的txt并创建对象?

javascript - 性能方面哪个更好 : An object protype or an constructors native function?

C# 文件 I/O 效率