I was able to set up the code so that the user chooses from the cases but I am confused with how I go about implementing the code into each case. For the first case I need to find the number of digits in an integer using "getnumdigits". I keep getting the error saying "jump bypasses variable initialization". I am wondering where my mistake can be fixed before I attempt to proceed to the next cases.
#include <iostream>
#include <cstdlib>
using namespace std;
int main ()
{
//declare a choice from the menu
int choice;
//Display choice menu
do {
cout << "Choose 1 to find the number of digits in an integer." << endl;
cout << "Choose 2 to find the nth digit in an integer." << endl;
cout << "Choose 3 to find the sum of all digits of an integer." << endl;
cout << "Choose 4 to quit this program." << endl;
cin >> choice;
switch (choice)
{
case 1:
int number;
int getNumDigits = 0;
cout << "Enter a positive integer: " << endl;
cin >> number;
while (number < 0) {
cout << "Invalid number entered." << endl;
cout << "Enter a positive integer: " << endl;
cin >> number;
}
while (number > 0)
{
number = number / 10;
getNumDigits++;
}
cout << "Number of digits in " << number << ": " << getNumDigits << endl;
return 0;
break;
case 2:
break;
case 3:
break;
case 4:
cout << "End of program." << endl;
break;
default:
cout << "Not a valid choice." << endl;
}
} while (choice != 4);
I was trying to write my first function inside of a case before moving to next cases. So that when I test/compile I could see if I was on the right track.
#include <iostream>
#include <cstdlib>
usingnamespace std;
int main ()
{
//declare a choice from the menu
int choice;
int number;
int getNumDigits = 0;
//Display choice menu
do {
cout << "Choose 1 to find the number of digits in an integer." << endl;
cout << "Choose 2 to find the nth digit in an integer." << endl;
cout << "Choose 3 to find the sum of all digits of an integer." << endl;
cout << "Choose 4 to quit this program." << endl;
cin >> choice;
switch (choice)
{case 1:
cout << "Enter a positive integer: " << endl;
cin >> number;
while (number < 0)
cout << "Invalid number entered." << endl;
cout << "Enter a positive integer: " << endl;
cin >> number;
while (number > 0)
number = number / 10;
getNumDigits++;
cout << "Number of digits in " << number << ": " << getNumDigits << endl;
return 0;
break;
case 2:
break;
case 3:
break;
case 4:
cout << "End of program." << endl;
break;
default:
cout << "Not a valid choice." << endl;
}}
while (choice != 4);
return 0;
}