Reputation: 3
You have to write an ITERATIVE procedure write_digit(d,x) that receives a digit d and a natural number x, and writes x times the digit d in the standard output (cout). For example, the call write_digit(3,5) writes 33333, whereas the call write_digit(5,3) writes 555.
I have problem with this code and it has to do with leading zeroes. Example: write_digit(0,3) -> 000 -> My output: 0 (not a surprise)
The problem would be resolved in 1 minute if I was allowed to use iomanip
if (d == 0) cout << setw(x) << setfill('0') << "";
However, I CAN ONLY USE iostream and string.
#include <iostream>
using namespace std;
void write_digit(int d,int x) {
int original_d = d;
for (int i = 1; i < x; ++i) d = d*10 + original_d;
if (x == 0) cout << "";
else cout << d;
}
int main () {
int d,x;
cin >> d >> x;
write_digit(d,x);
}
Upvotes: 0
Views: 41
Reputation: 49008
You are completely overcomplicating the assignment, just make a simple loop without any edge conditions, it will work for any number, even for non-digits.
void write_digit(int d, int x) {
for (int i = 0; i < x; ++i) // Loop x times
std::cout << d; // Output digit
std::cout << '\n'; // Output newline
}
Upvotes: 1