I have the following code:
float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
cin >> x1;
cin.ignore(1, ',');
cin >> y1;
cin >> x2;
cin.ignore(1, ',');
cin >> y2;
cout << "Coordinates registered as (" << x1 << "," << y1 << "), (" << x2 << "," << y2 << ").\n";
But this always returns (0,0) (0,0).
What would the correct implementation of cin.ignore be?
If you are literally entering in the data in the form of (x1,y1) (x2,y2)
like
(10,20) (30,40)
Then you are going to need to consume the parenthesis as well as the commas. A simple way to do this is to declare a char variable and use that to get the single characters that needs to be removed
float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
std::cin >> eater; // removes (
std::cin >> x1;
std::cin >> eater; // removes ,
std::cin >> y1;
std::cin >> eater; //removes )
std::cin >> eater; // removes (
std::cin >> x2;
std::cin >> eater; // removes ,
std::cin >> y2;
std::cin >> eater; //removes )
To make it a little more compact you can get one coordinate per line like
float x1 = 0,x2 = 0,y1 = 0,y2 = 0;
char eater;
std::cout << "Enter coordinates as \"(x1,y1) (x2,y2)\"\n";
std::cin >> eater >> x1 >> eater >> y1 >> eater;
// ( , )
std::cin >> eater >> x2 >> eater >> y2 >> eater;
// ( , )
I like to leave the comment in there to to express what should be being consumed each time you get the input.