给定用户输入整数的 C++ 打印空格或制表符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15884284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:50:53  来源:igfitidea点击:

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

c++tabs

提问by Slider

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

我需要将用户输入(一个数字)转换为 TAB 空格的输出。我问用户的例子:

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

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

(n) 我需要把它变成一个输出,如:

cout << n , endl; 

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

屏幕上打印的是空格 ex input is 5 out put | _| <~~~那里有五个空格。

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.

任何帮助将不胜感激。

回答by James Kanze

Just use std::string:

只需使用std::string

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

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

然而,在许多情况下,根据接下来发生的情况,n将参数添加到std::setw.

回答by taocp

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;

回答by Joseph Mansfield

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

您只需要一个循环来迭代由给出的次数n并每次打印一个空格。这会做:

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

回答by StahlRat

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

我只是碰巧寻找类似的东西并想出了这个:

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

回答by killscreen

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

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