提问者:小点点

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


我有一个代码是这样的

#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次打印('*'),请帮帮我


共2个答案

匿名用户

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

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

匿名用户

如注释中所述,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;
}

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(何在|c++|中|打印|字符|字符串)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?