I'm trying to write a program that asks the user for a number between 1 and 10, then prints a line of that many “X"s.

The program compiles, but I cannot figure out how to make the variable 'total' print X's instead of a the actual number, if that makes any sense. Thanks in advance.

#include <iostream>
#include <string>
using namespace std;
int main ()
{
int numExs;
string totalxs;
cout << "Please enter the number of Xs (1-10): ";
cin >> numExs;
if (numExs >= 1 && numExs <= 10)
{
int total = 0;
for (int x = 1; x <= numExs; x++)
{
total += x;
totalxs = total * 'X';


}
cout << totalxs;
}
else
{
cout << "Please follow the directions! " << endl;
}
}

Well, your code can be easily fixed, change:

for (int x = 1; x <= numExs; x++)
{
total += x;
totalxs = total * 'X'; [B]// (1)[/B]
}

to:

for (int x = 1; x <= numExs; x++)
{
totalxs += 'X';
}

(1): Wrong steps:

  1. You multiply an ASCII value, first the character will be implicitly converted to an integer (representing it's ASCII value), that integer will be multiplied by the value in variable total, the result of the multiplication will be implicitly converted back to a character, and then that character will be put into the string (overwriting the previous value).
  2. Each time you overwrite the existing value in the string

:)

thanks tux! it works great now!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.