[c++] C++ printing spaces or tabs given a user input integer

I need to turn user input (a number) into an output of TAB spaces. Example I ask user:

cout << "Enter amount of spaces you would like (integer)" << endl;
cin >> n;

the (n) i need to turn it into an output like:

cout << n , endl; 

and what prints on the screen would be the spaces ex input is 5 out put |_| <~~~there are five spaces there.

Sorry If I can't be clear, probably this is the reason I haven't been able to find an answer looking through other people's questions.

any help will be greatly appreciated.

This question is related to c++ tabs

The answer is


Simply add spaces for { 2 3 4 5 6 } like these:

cout<<"{";

for(){
    cout<<" "<<n;    //n is the element to print !
}

cout<<" }";

Just use std::string:

std::cout << std::string( n, ' ' );

In many cases, however, depending on what comes next, is may be simpler to just add n to the parameter to an std::setw.


You just need a loop that iterates the number of times given by n and prints a space each time. This would do:

while (n--) {
  std::cout << ' ';
}

Appending single space to output file with stream variable.

// declare output file stream varaible and open file ofstream fout; fout.open("flux_capacitor.txt"); fout << var << " ";


I just happened to look for something similar and came up with this:

std::cout << std::setfill(' ') << std::setw(n) << ' ';