【问题标题】:How to print a character or string in multiple times in c++如何在 C++ 中多次打印一个字符或字符串
【发布时间】:2020-08-04 13:03:34
【问题描述】:

我的代码如下所示

#include <iostream>
#include <string>

using namespace std;

int main()
{
   int x;
   char chars = '*';
   cin >> x;

   for (int i=1; i<=x; i++){
       cout << chars * i << endl;
  }


    cout << "\n\n";
    system("pause");
    return 0;
}

它编译成功但是,当我运行它时,我只是显示这个

1
42

我想打印 ('*') x 次,请有人帮助我

【问题讨论】:

标签: c++ string


【解决方案1】:

要做你想做的事,你可以这样做:

#include <iostream>
#include <string>

using namespace std;

int main()
{
   int x;
   char chars = '*';
   cin >> x;

   for (int i=1; i<=x; i++){
       cout << chars;
  }

    cout << "\n\n";
    system("pause");
    return 0;
}

【讨论】:

    【解决方案2】:

    如 cmets 中所述 - char 乘以 int 得到 int

    下面的代码是你想要的吗?

    #include <iostream>
    
    int main()
    {
      int x;
      char const chars = '*';
      std::cin >> x;
    
      for (int i=1; i<=x; i++) std::cout << chars << std::endl;
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 2020-01-27
      • 1970-01-01
      • 2011-09-11
      相关资源
      最近更新 更多