'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.
Solution 1:[1]
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.
Solution 2:[2]
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 << ' ';
}
Solution 3:[3]
I just happened to look for something similar and came up with this:
std::cout << std::setfill(' ') << std::setw(n) << ' ';
Solution 4:[4]
You can use C++ manipulator setw(n) function which stands for set width to print n spaces.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
std::cin>>n;
cout<<"Here is "<<n <<" spaces "<<setw(n)<<":";
}
And don't forget to include C++ Library -
Solution 5:[5]
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 << " ";
Solution 6:[6]
Simply add spaces for { 2 3 4 5 6 } like these:
cout<<"{";
for(){
cout<<" "<<n; //n is the element to print !
}
cout<<" }";
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | roalz |
| Solution 2 | Joseph Mansfield |
| Solution 3 | StahlRat |
| Solution 4 | shashikant dev |
| Solution 5 | bananaforscale |
| Solution 6 | B. Go |
