C++ manually Convert string to int? -
i trying manually convert string int, , have had difficulties. first check see if string entered integer. next, want convert string integer without using library methods.
when ran code inside loop line line, did needed to, when ran inside loop, spat out incorrect binary results.
==> going check if value enter number.
==> enter number: 234
==> input result: 1
==> press enter continue...
==> 11001
// darian nwankwo, random programs, august 2, 2015 #include <iostream> #include <string> #include <cmath> int main(int argc, const char * argv[]) { std::string number = ""; bool isnumber = false; std::cout << "i going check if value enter number." << std::endl; std::cout << "enter number: "; std::cin >> number; std::cin.ignore(); // iterate through variable number check if number ( int = 0 ; < number.length() ; i++ ) { if ( number[i] < 48 || number[i] > 57) { break; } else { isnumber = true; } } std::cout << "input result: " << isnumber << std::endl; int newnumber = 0; // iterates on number string variable , converts value integer if (isnumber) { ( int = 0 ; < number.length() ; i++ ) { // newnumber += std::pow( 10.0, number.length() ) newnumber = std::pow(10.0, ( number.length() - ( + 1 ) ) * ( number[i] - '0' )); } } else { std::cout << "can't convert." << std::endl; } char cont; std::cout << "press enter continue..." << std::endl; std::cin.get(cont); std::cout << newnumber; return 0; }
change loop to:
( int = number.length() -1 ; >= 0 ; i-- ) { int power = number.length() - -1; newnumber += (std::pow( 10.0, power) * (number[i] - '0'));
and make newnumber double.
hope helps !!
Comments
Post a Comment