I have created this program to convert string to float the program run ok but when I try 1995.1995 it output 1995.2 but it works for other strings like 1 can any explain the reason?
#include <iostream>
#include <iomanip>
using namespace std;
bool isValid(char c) {
if (c == '.')
return true;
if (c >= '0' && c <= '9')
return true;
return false;
}
int main()
{
char input = '0';
while (isValid(input)) {
float result = 0;
bool isFraction = false;
float divideBy = 1;
cout << "please enter string to convert : " << endl;
cin >> input;
while (true)
{
if (input == '.') {
isFraction = true;
}
else {
int intInput = input - '0';
if (isFraction) {
divideBy = divideBy * 10;
result = result + intInput / divideBy;
}
else {
result = result * 10 + intInput;
}
}
if (cin.peek() == '\n')
break;
cin >> input;
}
cout << "Your input is : " << result << endl;
}
return 0;
}