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.
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>
usingnamespace 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;
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';
}
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