Spaces placed in output

So in this project I'm supposed to output a char, input by the user, a number of times input by the user. I can do that fine enough but there's supposed to be a space between each character, but not at the beginning or end of the line. I'm not quite sure how to do it. Any advice would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    GNU nano 2.9.8                      lab05.cpp

// Lab 05
// We are prompting the user to input a char, and
// an integer which will be the number of times the
// char repeats.

#include <iostream>
#include <iomanip>
using namespace std;

int main(){

char c;
int n = 0;

  //prompt the user for needed information
  cout << "Please enter a single character" << endl;
  cin >> c;
  cout << "Please enter the number of times it will repeat." << endl;
  cin >> n;

  // Here we make a loop to produce the needed output.
  int counter =0;

  while(counter <= n){
    cout << c;
    counter++;
  }

  cout << endl;
Print the final character outside of the loop.
1
2
3
4
5
6
int counter = 0;
while (counter <= n - 1) {
   cout << c << ' ';
   counter++;
}
cout << c << '\n';


Btw, when you say "number of times the char repeats" does that mean n = 6 means 6 total, or 1 initial character + 6 repetitions? The code above does the latter since that's what your code appears to be doing.

If you only wanted n characters to be printed, you could do:
1
2
3
4
5
6
7
8
9
if (n > 0)
{
    int counter = 0;
    while (counter < n - 1) {
       cout << c << ' ';
       counter++;
    }
    cout << c << '\n';
}
Last edited on
If I understand your question, maybe:

1
2
3
4
5
if (n > 0) {
    cout << c;
    while (--n > 0)
        cout << ' ' << c;
}

Thank you both very much.
Hello DevonMeep,

I will make 2 points.

1
2
3
4
5
6
while (counter <= n)  // <--- The (<=) will do 1 loop more than you may want.
{
    cout << c << ' ';  // <--- By adding the space it will put a space between the letters. 
                       // The space after the final letter is not noticed or seen on the screen.
    counter++;
}


The change did produce this output:

Please enter a single character
X
Please enter the number of times it will repeat.
6
X X X X X X X 



Another suggestion: cout << "Please enter a single character" << endl;. If you remove the "endl" this would put the "cin" on the same line. cout << "Please enter a single character: ";. The (: ) is what I tend to use the most. You may use anything you like for the prompt character.

Changed the output is:

Please enter a single character: X
Please enter the number of times it will repeat.: 6

X X X X X X X 


Something to consider.

Andy
Topic archived. No new replies allowed.