|
-
November 13th, 2016, 11:58 PM
#1
Convert any input of length measurement into meters C++
Given:
1 foot = 0.305 m
1 in = 0.0254m.
I am attempting to convert the input of length measurements into meters.
For example: 5'1'' = 5*0.305 + 1 * 0.0254 = 1.5504m
3.4m = 3.4m
5'1.23456" = 5*0.305 + 1.23456*0.0254 = 1.5563
But I have got quite a few errors. I don't know how to fix them but here is my logics on how to approach this puzzle.
I wrote some if statements to take care of:
1) If I input only, say 3.4, it will print the whole string and convert it into double 3.4.
2) If I input, say 5'1" without no "."
)If I input, say 5'1.23" with " . ",
But I failed. I need your help to point out the problems of my code. Thanks in advance!
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <sstream>
using namespace std;
double convert_String(string&);
int main()
{
string s;
getline(cin,s);
convert_String(s);
return 0;
}
double convert_String(string& s)
{
string s1,s2;
int y1, y2,y3;
double d1,d2,d3;
int l = s.length();
y1 = s.find("."); // find the position of the "." and then assign the position value to y1
y2 = s.find("'"); // find the position of the " ' " and then assign the position value to y
y3 = s.find('"'); // find the position of the " " " and then assign the position value to y2
if ((y1 < 0 && y2 < y1 && y3 == l) || (y2 < 0 && y3 < 0 && y1 == -1))
{
s1 = s.substr(0,y2-1);
d1 = stod(s1);
d1 = d1*0.305;
s2 = s.substr(y2+1,l-1);
d2 = stod(s2);
d2 = d2*0.0254;
}
else if(y2 == -1 && y3 == -1 && y1 >= 0) //there is no " ' " and " " "
{
d3 = stod(s);
}
cout << d1 << endl;
return d1 + d2;
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|