【问题标题】:Need help printing a sequence, without spaces, on the same line需要帮助在同一行打印一个没有空格的序列
【发布时间】:2012-04-09 09:30:21
【问题描述】:

这就是我正在使用的。

#include <iostream>

using namespace std;

int main()
{
    int i, h = -1;

    for (i = 0; i < 8; i++) {
        h = h + 1;
        cout << h << endl;
    } // while

    return 0;
} // main

我需要我的输出看起来像

1 2 3 4 5 6 7 

但我得到了

1
2
3
4
...

除了endl,还有什么可以用来打印到带有空格的同一行吗?感谢和抱歉这个菜鸟问题。我正在慢慢学习 C++。

【问题讨论】:

标签: c++ for-loop endl


【解决方案1】:

听起来你想打印每个数字,中间有一个空格。如果是这样,则使用实际空格而不是行尾字符

cout << h;
cout << ' ';

然后在循环结束时显式添加新行

cout << endl;

完整样本

  int i;
  for (i = 0; i < 8; i++)
  {
    h = h +1 ;
    cout << h << ' ';
  } 
  cout << endl;

【讨论】:

    【解决方案2】:

    cout

    【讨论】:

    • 一个空格' '就够了。
    【解决方案3】:

    endl 是打印换行符的内容,因此您应该将其放在循环之外。示例:

    for (i = 0; i < 8; i++)
    {
      h = h + 1;
      cout << h;
    }
    cout << endl;
    

    【讨论】:

    • 这将打印01234567,可能不是 OP 想要的。
    • @hochl:你说得对,我刚刚读到“without 空格”的问题标题...
    猜你喜欢
    • 2013-02-12
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 2021-05-31
    • 2018-07-19
    相关资源
    最近更新 更多