C++ printing spaces or tabs given a user input integer

可紊 提交于 2020-12-30 06:11:36

问题


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.


回答1:


cout << "Enter amount of spaces you would like (integer)" << endl; 
cin >> n;
//print n spaces
for (int i = 0; i < n; ++i)
{
   cout << " " ;
}
cout <<endl;



回答2:


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.




回答3:


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



回答4:


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

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



回答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 << " ";




回答6:


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

cout<<"{";

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

cout<<" }";


来源:https://stackoverflow.com/questions/15884284/c-printing-spaces-or-tabs-given-a-user-input-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!