hi i am having trouble having 0 loop at the beginning if i type in 01234
it will just output -1-22-333-4444 but when i type in 1023 it will show 1-0-22-333 correctly. ive been trying to create a statement that would make 0 = 1 then output using cout <<"0"; i believe the problem is in if (b == count)
#include <iostream>
#include <cmath>
usingnamespace std;
int main ()
{
int num;
char choice;
do {
int count = 0, remain, quotient;
cout << "\nEnter an integer value: ";
cin >> num;
if (num <= 0 || num >= 2147483647) // maximum storage memory for int
cout << "\nInvalid number!\n";
else {
for (int a = num; a != 0; ++count) { // counts number of digits
a /= 10;
}
for (int b = count; b > 0; b--) { // isolates each digit
quotient = num / (int) pow(10, b - 1);
remain = num % (int) pow(10, b - 1);
if (b == count)
cout << "";
else
cout << "-";
if (quotient == 0)
cout << "0";
for (int c = quotient; c > 0; c--) { // repeats digits according to their value
cout << quotient;
num = remain;
}
}
cout << "\n\nEnter <y>es to continue or <n>o to discontinue: ";
cin >> choice;
}
} while (choice == 'y' || choice == 0);
cout << "\nProgram ended\n";
}
The number 012345 is stored as just an int. Its the same number as 12345 or 00000012345 (ignoring octal notation).
You would have to originally store the "number" as a string, to keep the leading zero info.
// Example program
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string num;
std::cin >> num; // input the "number" as a string
for (int i = 0; i < num.length(); i++)
{
// store character of the string into a
// stringstream for later conversion
std::stringstream ss;
ss << num[i];
// convert the character into an int:
int n;
if (ss >> n) // check success of conversion
{
// print the character out n times:
for (int i = 0; i < n; i++)
{
std::cout << n;
}
std::cout << std::endl;
}
}
}