"class" c++

Hello :) , I need help assigning numbers from txt to vector "vec" and passing it to class Triangle.

numbers in txt: 5 5 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  #include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

class Triangle
{
  public:
   vector <int> vec;

   string point()
   {
     if (vec[0] == vec[1] && vec[0] == vec[2])
     {
       return "every side is equal";
     }
     else
     {
       return "every side is not equal";
     }
   }
   
};

int main() 
{
  vector <Triangle> vec;

  ifstream ok;
  ok.open("triangle.txt");
  
  

  return 0;  
}
Last edited on
First off, you need a constructor for Triangle that accepts 3 sides:
11
12
13
14
15
16
17
//  Constructor
    Triangle(int s1, int s2, int s3)
    {
        vec.push_back(s1);
        vec.push_back(s2);
        vec.push_back(s2);
    }


Then you need a read loop:
32
33
34
35
36
37
38
39
40
    while (ok.good())
    {   int s1, s2, s3;
        ok >> s1 >> s2 >> s3;
        if (ok.good())
        {
            Triangle temp(s1, s2, s3);
            vec.push_back(temp);
        }
    }


Line 10: Using a std:vector to keep track of the three sides seems like overkill. Three ints would be perfectly adequate.
Last edited on
First off, you need a constructor for Triangle that accepts 3 sides:

Actually the code in the OP doesn't need a constructor of any kind since everything in that class is currently public. However since that class is really not well designed a constructor will probably be required when a little more thought goes into that class.

And there is probably no need to have a vector<Triangle> in main().

I forgot to say that I have to use vector...
I figured it out :) Thank you for Helping me :)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;

class Triangle
{
  public:
   vector <int> vec;
   string func()
   {
     if (vec[0] == vec[1] && vec[0] == vec[2])
     {
       return "every side is equal";
     }
     else
     {
       return "every side is not equal";
     }
   }
   
};

int main() 
{
  ifstream ok;
  ok.open("triangle.txt");
  int a;
  Triangle key;

  for (int i = 0; i < 3; i++)
  {
    ok >> a;
    key.vec.push_back(a);
    cout << key.vec[i];
  }
  cout << endl;
  cout << key.func();
  ok.close();
  return 0;  
}
Topic archived. No new replies allowed.