I was trying to manually convert a string to an int, and I have had difficulties. I first check to see if the string entered is an integer. Next, I want to convert that string to an integer without using any library methods.
When I ran the code inside my loop line by line, it did what I needed it to, but when I ran it inside a loop, it spat out incorrect binary results.
==> I am going to check if the value you enter is a number.
==> Enter a number: 234
==> Input result: 1
==> Press enter to 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 am going to check if the value you enter is a number." << std::endl; std::cout << "Enter a number: "; std::cin >> number; std::cin.ignore(); // Iterate through variable number to check if it is a number for ( int i = 0 ; i < 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 over the number string variable and converts value to an integer if (isNumber) { for ( int i = 0 ; i < number.length() ; i++ ) { // newNumber += std::pow( 10.0, number.length() ) newNumber = std::pow(10.0, ( number.length() - ( i + 1 ) ) * ( number[i] - '0' )); } } else { std::cout << "Can't convert." << std::endl; } char cont; std::cout << "Press enter to continue..." << std::endl; std::cin.get(cont); std::cout << newNumber; return 0; }