The following is the code that I am working on -
#include <iostream>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iterator>
using namespace std;
struct coord {
long x,y;
};
int main()
{
ifstream nos("numbers.txt");
vector< long > values;
double val;
while ( nos >> val )
{
values.push_back(val);
}
copy(values.begin(), values.end(), ostream_iterator<double>(cout, "\n" ));
return 0;
}
I understand the initial struct is not necessary here, but I wish to use that. I want my input text file to be something like this -
1,2
2,3
4,5
I then use my program, to input these numbers into a vector and print out that vector in the same format
Could anyone tell me what's the correct way of doing so?
I have referred to the following for the code, but I need to read and print out in the format mentioned above and I am not sure what's the best way to proceed.
For better clarity - I am attempting to implement a convex hull algorithm. I am trying to get better at programming at the same time and hence such a jump.
Question: Why are you mixing double
and long
? I'll assume you want to use long
throughout the code. The easiest way to do what you want is to add a dummy variable that reads the ,
between the numbers:
int main()
{
ifstream nos("numbers.txt");
vector< long > values;
long val1, val2;
char dummy;
while ( nos >> val1 >> dummy >> val2)
{
values.push_back(val1);
values.push_back(val2);
}
copy(values.begin(), values.end(), ostream_iterator<long>(cout, "\n" ));
}
Also, you defined a struct named coord
, but you don't use it in the code. If you would like to use that, you could use the following code:
std::ostream& operator<<(std::ostream& os, const coord& c)
{
os << c.x << " " << c.y;
return os;
}
int main()
{
ifstream nos("numbers.txt");
vector< coord > values;
coord c;
char dummy;
while ( nos >> c.x >> dummy >> c.y )
{
values.push_back(c);
}
copy(values.begin(), values.end(), ostream_iterator<coord>(cout, "\n" ));
}
Also, in C++11 you could change the code to:
long x, y;
char dummy;
while ( nos >> x >> dummy >> y )
{
values.emplace_back(coord{x, y});
}
Or you could also look into std::pair<long, long>
for placing your coordinates in.