Why is my C++ program only printing one character?

After a long back and forward in the comments, the OP explained what was his purpose. To generate random words of the same size as input and stop when it matched the input.

This code does what you want. It’s in c++14 so you need a recent compiler and to set the c++14 option. Please note the actual use of random.

#include <iostream>
#include <string>
#include <random>
#include <algorithm>

using std::cin;
using std::cout;
using std::cerr;
using std::endl;

class RandomCharGenerator {
  static std::string s_chars_;

  std::random_device rd_{};
  std::default_random_engine r_eng_{rd_()};
  std::uniform_int_distribution<int> char_dist_{
      0, static_cast<int>(s_chars_.size())};

  RandomCharGenerator() = default;

  auto getRandomChar() -> char { return s_chars_[char_dist_(r_eng_)]; }
  auto setRandomString(std::string &str) -> void {
    std::generate(std::begin(str), std::end(str),
                  [this] { return this->getRandomChar(); });

std::string RandomCharGenerator::s_chars_ = "abcdefghijklmnopqrstuvwxyz";

auto main() -> int {
  RandomCharGenerator rand_char;

  auto input = std::string{};

  cin >> input;
  auto generated = std::string(input.size(), ' ');

  do {
    cout << generated << endl;
  } while (input != generated);

  cout << "We generated what you input" << endl;
  return 0;

For input longer than 4 characters it takes a long time to generate the input.

Ideone demo

To understand why you had only 1 char in your Passwords:

Passwords = Alpha + I;

Alpha is a char, I is an int. Their sum is an int. This is converted to char when assigning to Passwords which is a string. So Passwords is now a string composed of only one char.

It’s not clear what that actual line of code was supposed to do, so can’t tell you what would have been the fix. Maybe you meant to append to Passwords. Then you should have written Passwords += Alpha + I.

Browse More Popular Posts

Leave a Comment