简体   繁体   English

C++ 的第一天

[英]First day at C++

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 我需要它循环回来并再次询问他们。

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();
    }
}
#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.我选择了一个 do/while 循环,因为我总是需要至少一次获得首字母。

The variable bogusInput is a flag that I use to know if something hasn't worked out properly.变量bogusInput是一个标志,我用它来知道某些事情是否没有正确解决。 It is declared outside of the loop for the sake of the while condition.为了 while 条件,它在循环之外声明。 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.最后,“有效”输入让我们退出循环,我们说谢谢并结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM