Alvin-Pranata
Alvin-Pranata

Reputation: 23

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

Upvotes: 0

Views: 2147

Answers (2)

Davide Vacirca
Davide Vacirca

Reputation: 26

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

Upvotes: 1

Łukasz Ślusarczyk
Łukasz Ślusarczyk

Reputation: 1864

As stated in comments - char when multiplied by int results in 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;
}

Upvotes: 1

Related Questions