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

Dani AI

Generated

A clear, direct way to get "N" copies of the character 'X' is to build the string from the input value instead of trying to do arithmetic with the character. The original code introduced an extra accumulator and then attempted to multiply a char by an integer, which does not produce repeated characters. 's fix (appending characters) is perfectly fine; here are concise, idiomatic alternatives and a few practical tips.

A compact option is to construct the string with a repeat-count constructor:

std::string xs(numExs, 'X');
std::cout << xs << '\n';

Or use assign to replace the contents with N copies:

std::string xs;
xs.assign(numExs, 'X');

Both approaches are simple and efficient. See the std::string constructor documentation for details.

Do validate input and handle bad extraction before building the string. For loop-based building, call reserve(numExs) first to avoid repeated reallocations when numExs might be large. For this small 1–10 range reallocation is trivial, but reserving is a good habit when sizes are unknown.

To tie back to the thread: the core bug was using a numeric accumulator and character arithmetic instead of directly using the requested count. Either append in a loop (as suggested) or use one of the concise constructors above for clearer, more robust code.

Recommended Answers

All 2 Replies

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.