How could I type type the midpoint with or without parenthesis, It works when I type with parenthesis (6,7) but when I don't use a parenthesis 6,7 it doesnt work.
#include <iostream>
#include <limits>
using namespace std;
double midpoint (double x1, double x2);
int main()
{
double X1,X2,Y1,Y2, midpoint1, midpoint2;
char t, yes_no;
cout << "Welcome to the mid-point program!\n";
cout << "Would you like to find a midpoint?\n";
cin >> yes_no;
cin.ignore(numeric_limits<streamsize> ::max(),'\n');
while (toupper (yes_no)=='Y')
{
cout << "please enter the value of your 1st end point\n";
cin >> t >> X1 >> t >> Y1 >> t;
cout << "please enter the value of your 2nd midpoint\n";
cin >> t >> X2 >> t >> Y2 >> t;
midpoint1 = midpoint(X1, X2);
midpoint2 = midpoint(Y1, Y2);
cout << "the midpoint of the line is (" << midpoint1 << ", " <<midpoint2
<< ")." << endl << endl;
cout << "Do you want to find another midpoint?\n";
cin >> yes_no;
cin.ignore(numeric_limits<streamsize> ::max(),'\n');
}
cout << "Have a great day!" << endl;
Currently, your code can only accept input in the form of cin >> t >> X1 >> t >> Y1 >> t;
char double char double char
If you want to be able to accept different kinds of input, you will have to accept the entire line of input as a string and then examine it yourself in code to work out what the numbers you care about are.
#include <iostream>
#include <utility>
// return true if the next character extracted and discarded is the expected character
bool got_expected( std::istream& stm, char expected )
{
char c = 0 ;
return stm >> c && c == expected ;
}
// extract and discard the next character if it is to_be_discarded
// return true if to_be_discarded was extracted and discarded
bool ignore_if( std::istream& stm, char to_be_discarded )
{
char c = 0 ;
// read the next char, discard it if it is to_be_discarded, otherwise put it back
if( stm >> c && c != to_be_discarded ) stm.putback(c) ;
return c == to_be_discarded ;
}
// accepts input of the following forms: (x,y) or x,y or (x y) or x y
// the input format is free: extra white spaces may be present anywhere
std::istream& get_coordinates( std::istream& stm, std::pair<double,double>& coords )
{
// true if an open parenthesis at the beginning was found and discarded
constbool open_paren = ignore_if( stm, '(' ) ;
// try to read the two floating point values separated by either a comma or white space
stm >> coords.first ; // read the first number
ignore_if( stm, ',' ) ; // ignore a comma, if it is present
if( stm >> coords.second ) // if a second number was also successfully read
{
// if there was an open parenthesis, there must be a close parenthesis at the end
// if not, place the stream into a failed state
if( open_paren && !got_expected( stm, ')' ) ) stm.clear( stm.failbit ) ;
}
return stm ;
}