简体   繁体   English

c++中如何多次打印一个字符或字符串

[英]How to print a character or string in multiple times in c++

I have a my code that's look like this我的代码看起来像这样

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

and it compiled succesfully but, when I run it i just display this它编译成功但是,当我运行它时,我只显示这个

1
42

and I want to print ('*') in x times, please someone help me我想在 x 次中打印 ('*'),请有人帮助我

To do what you want you can do this:做你想做的事,你可以这样做:

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

As stated in comments - char when multiplied by int results in int .如评论中所述 - char乘以int结果为int

Is below code what you wanted?下面的代码是你想要的吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM