My program does not work (subprograms and leading zeroes)

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#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);
}


A new problem with this code has risen and it has to do with leading zeroes. Example:
write_digit(0,3) -> 000 -> My output: 0

The problem would be resolved in 1 minute if I was allowed to use <iomanip>
if (d == 0) cout << setw(x) << setfill('0') << "" << endl;
However, I CAN ONLY USE <iostream> and <string>
Last edited on
What is wrong in the:
1
2
3
4
for ( int foo = 0; foo < 3; ++foo ) {
  std::cout << 0;
}
std::cout << '\n';
Hello Oriol Serrabassa,

Try putting the if else in write_digit inside the for loop and see what happens.

Hope that helps,

Andy
Topic archived. No new replies allowed.