make user enter a string of integers and output a different string

For most digit manipulation assignments, I recommend treating the number as a string of characters rather than as a number.

The Foundation

Let’s start with the foundation:

#include <iostream>
#include <string>
#include <cstdlib>

using std::cout;
using std::cin;
using std::getline;

int main(void)
  cout << "Paused.  Press Enter to continue.\n";
  cin.ignore(100000, '\n');
  return EXIT_SUCCESS;

The above program will hopefully keep the console (terminal) window open until the Enter key is pressed.

Getting The Input

We’ll ask the User for a number, this is also known as prompting:

// The prompt text doesn't change so it's declared as const.
// It's declared as static because there is only one instance.
static const char prompt[] = "Enter a number: ";
cout.write(prompt, sizeof(prompt) - 1U); // Subtract 1 so the terminating nul is not output.

// Input the number as text
string number_as_text;
getline(cin, number_as_text);

Printing The Digits

Really, before this step, you should verify that the text only contains numbers. Repeat the prompting until the User inputs nothing or valid data.

A string can be accessed as an array. So we’ll set up a loop:

const unsigned int length = number_as_text.length();
for (unsigned int index = 0U;
     index < length;
  // Extract the digit.
  const char c = number_as_text[index];

  // Verify it is a digit.
  if (!isdigit(c))

  unsigned int quantity = c - '0'; // Convert to a number.
  if (quantity == 0) quantity = 1; // The requirements lie, for zero there is a quantity of 1.

  // Use "quantity" to print copies of the character.

cout << "\n";


I’m not going to write the entire program for you, as you haven’t paid for my services. So you will have to figure out when to print the ‘-‘ and how to print many copies of the digit.

If this answer is not correct, please update your question with some clarifications or restrictions.

Leave a Comment