Home > Mobile >  How does one allow the user to input feet and inches with an apostrophe inbetween?
How does one allow the user to input feet and inches with an apostrophe inbetween?

Time:08-29

For example if we have something like this in the code

int height;

cin >> height;

user inputs

5'9

How would I go about making that work?

It would be easy enough to have

cin >> feet;

cin >> inches;

cout << feet << "'" << inches << "\n\n";

and put it together but it's just not that neat or practical of a program for the end user.

How would I be able to make it so the user can type 5'9 with the apostrophe, and still have the code understand it and use it?

Essentially what I would need it to understand is that the 5 represents 12*5 (12 inches in a foot) the 9.

Thank you in advance!

CodePudding user response:

This is one way

int feet, inches;
char apos;

cin >> feet >> apos >> inches;

The apos variable is there to read the '. This code has no error checking, you can add that if you like (including checking that apos really is an apostrophe).

if ((cin >> feet >> apos >> inches) && apos == '\'')
{
     // do something with feet and inches
     ...
}
else
{
     // some kind of error handling
     ...
}
  •  Tags:  
  • c
  • Related