0

I need to ask for the user's Initials and have it return their input. If they input any int I need it to loop back and ask them again.

int main()
{
    // Program 1-1

    std::cout<<"Hello, can you please enter your initials?\n";
    char initials[50];
    std::cin.getline(initials, 50);

    while (std::cin != int)
    {
        std::cout << "Thank you. " << initials << std::endl;
    }
    else (std::cin.fail())
    {
        std::cin.clear();
    }
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
Andrew R
  • 11
  • 3
  • 9
    I'd recommend spending more time with a good book. Someone will drop the link. Ditch C-strings for `std::string`, your while condition is not legal, `else` doesn't have a Boolean expression, by definition (I don't think it's different in C#, or any other language for that matter), and that about covers what's shown. – sweenish Nov 23 '21 at 21:55
  • 7
    @sweenish here you go https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – trialNerror Nov 23 '21 at 21:59
  • @trialNerror Thank you! – sweenish Nov 23 '21 at 22:00
  • 1
    What is your question? – Adrian W Nov 23 '21 at 22:02
  • Thank you, yea only been coding for 2 months so still really fresh and google can only help so much. – Andrew R Nov 23 '21 at 22:53

1 Answers1

2
#include <cctype>
#include <iostream>
#include <string>

int main() {
  std::string tmp;

  bool bogusInput;
  do {
    std::cout << "Initials: ";
    std::getline(std::cin, tmp);

    bogusInput = false;

    for (auto i : tmp) {
      if (std::isdigit(i)) {
        bogusInput = true;
        break;
      }
    }

    if (bogusInput) {
      std::cout << "Are you Elon's son? Please enter letters only.\n";
    }
  } while (bogusInput);

  std::cout << "Thank you, " << tmp << ".\n";

  return 0;
}

This code does the job you describe. I chose a do/while loop since I always need to get initials at least one time.

The variable bogusInput is a flag that I use to know if something hasn't worked out properly. It is declared outside of the loop for the sake of the while condition. It is always reset before performing the check, this allows the case of multiple attempts to work.

Finally, "valid" input gets us out of the loop and we say thank you and end.

sweenish
  • 4,793
  • 3
  • 12
  • 23