在For循环中遍历C ++向量

威廉·巴恩斯

我的代码出了点问题。它正在编译,但是结果不是我所期望的,尽管我可以确定我的问题之一,但是我想知道我是否走错了方向。

我创建了一个名为test的类:

`
class test{

private:

//have moved the variables to public 
//so it's easy to see what's in the vector. 

public:

    int my_id, my_x,my_y,width, height;

test (int button_id=0, int x=0, int y=0, int width=0, int height=0)
{
    my_x = x;
    my_y = y;

    width = width;
    height = height;

}

~test()
{}

void handle_event()
{}

};

`

现在我想用这些对象填充向量,并从文本文件中初始化它们的值。

这是我的方法:

int main(int argc, char const *argv[])
{

    //setup file
    ifstream inputFile("data.dat");
        const char* filename = "data.dat";
              std::ifstream inFile(filename);



    //init Vector
    vector<test> buttons;
        int id, x, y, width,height;
        int max_buttons = count(istreambuf_iterator<char>(inputFile),istreambuf_iterator<char>(), '\n');


    // Make sure the file stream is good
    if(!inFile) {
                cout << endl << "Failed to open file " << filename;
                return 1;
                }


  //Iterate fields into Vector,

  for (id=0 ; id < max_buttons ; id ++) 

  {

    inFile >> x >> y >> width >> height;

    buttons.push_back(test(id,x,y,width,height));    
    cout << std::setw(10) << x << y << width <<height <<endl;

  }

  cout << endl;

for(int p=0; p < 10; p++) // 

  cout << buttons[p].my_id << endl;

    return 0;
}

我已经将类中的变量移到了公共位置,因此查看它们会更容易,一旦发现问题,我便会将它们移回去。某些字段正确填充(x和y变量),但id不会随着每次调用而增加。我有一个完整的向量,但有废话数据。我意识到直接从文本文件中解析数据意味着它将采用char格式,并且与整数类型不兼容,但是为什么我的ID没有增加?

提前致谢!

这是数据:

23 16 10 19
24 40 10 17
23 16 10 16
25 40 10 14
26 16 10 10
27 40 10 12
27 36 10 11
28 40 10 13
29 34 10 18
27 49 10 10
好奇的

您没有在构造函数中更改对象的ID。因此将其更改为以下内容

test (int button_id=0, int x=0, int y=0, int width=0, int height=0)
{
    my_id = button_id;
    my_x = x;
    my_y = y;

    width = width;
    height = height;

}

试着与警告标志编译(如-Werror-Wall-pedantic等),使您的代码将被标记为在构造函数像未使用的变量的东西,你会知道你的错误之前就发生了!

另外,您不应该通过计算换行数来计算文件中的对象数,这有两个原因

  1. 如果某些地方没有换行怎么办?例如在某些物体之后。
  2. 它需要循环两次文件

您应该像下面这样循环:

while(inFile >> x >> y >> width >> height) { ... }

当文件中缺少4个变量中的任何一个时,它将返回false,因为istream它将进入“ false”状态,并且循环将自行停止

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章