简体   繁体   English

C++ 初学者:函数的小问题

[英]C++ Beginner: Minor Issues with Functions

I just started learning C++ and coming from no tech experience whatsoever, so please be patient with me.我刚开始学习 C++ 并且没有任何技术经验,所以请耐心等待。 Im using Codecademy to learn and encountered an issue with one of the exercises.我使用 Codecademy 学习并遇到了其中一个练习的问题。 I tried to create this function to remove repeating code in main() .我试图创建这个 function 以删除main()中的重复代码。

#include <iostream>
std::string on_off_attempt;
std::string IT_support(){
  std::cout << "Hello. IT\n";
  std::cout << "Have you tried turning it off and on again? y/ n\n";
  std::cin >> on_off_attempt;
  if (on_off_attempt == "y"){
    std::cout << "It should be working now!\n";
  }
  else if (on_off_attempt == "n"){
   std::cout << "Then please try again!\n";
  }
  else {
    std::cout << "Invalid Input!\n";
    std::cin >> on_off_attempt;
  }
  return on_off_attempt;
  }

As far as the first input, it works fine, but on the next input prompt, it no longer acknowledges the input for on_off_attempt and immediately just goes to the next output line.就第一个输入而言,它工作正常,但在下一个输入提示时,它不再确认on_off_attempt的输入,而是立即转到下一个 output 行。 Below is the main() code.下面是main()代码。

int main() {

  // Conduct IT support
  IT_support();

  // Check in with Jenn
  std::cout << "Oh hi Jen!\n";

  // Conduct IT support again...
 IT_support();

  // Check in with Roy
  std::cout << "You stole the stress machine? But that's stealing!\n";

  // Conduct IT support yet again...zzzz...
  IT_support();
}

Could anyone tell me what Im doing wrong?谁能告诉我我做错了什么? Any help would be appreciated: :)任何帮助,将不胜感激: :)

The reason why it goes directly to the next output line is because you never tell it to keep asking for input until it gets a valid one.它直接转到下一个 output 行的原因是因为您永远不会告诉它在获得有效输入之前一直要求输入。 You need a loop for that.你需要一个循环。 Something like this:像这样的东西:

std::string IT_support(){
  std::string on_off_attempt;
  bool inputValid = false;
  std::cout << "Hello. IT\n";
  std::cout << "Have you tried turning it off and on again? y/ n\n";
  while (!inputValid) {
    std::cin >> on_off_attempt;
    if (on_off_attempt == "y"){
      std::cout << "It should be working now!\n";
      inputValid = true;
    }
    else if (on_off_attempt == "n"){
      std::cout << "Then please try again!\n";
      inputValid = true;
    }
    else {
      std::cout << "Invalid Input!\n";
      inputValid = false;
    }
  }
  return on_off_attempt;
}

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

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