Getline代码无法正常工作或我的代码无法正确编译

时间:2019-09-19 02:39:36

标签: c++

我正在编写由用户输入公交路线及其出发时间组成的代码。我正在尝试使用std::getline()函数,因此,如果用户输入空格,它将正确输出。但是,我尝试编译我的代码,一切运行顺利,直到到达公交路线的第二个问题

heres a photo of it running

这是我要查看的代码,是否有人知道getline是问题还是其他原因:

#include <iostream>
#include <string>

int main() {

  std::string route1;
  std::string route2;
  std::string route3;

  int dept1 = 0, dept2 = 0, dept3 = 0;
  int time2leave = 0;

  std::cout << "Welcome to TuffyTravel!"<< std::endl;

  std::cout << "\nPlease enter the name of the 1st route: ";
  std::getline(std::cin, route1);
  std::cout << "Please enter the deptarture time of the 1st route: ";
  std::cin >> dept1;

  std::cout << "\nPlease enter the name of the 2nd route: ";
  std::getline(std::cin, route2);
  std::cout << "Please enter the deptarture time of the 2nd route: ";
  std::cin >> dept2;

  std::cout << "\nPlease enter the name of the 3rd route: ";
  std::getline(std::cin, route3);
  std::cout << "Please enter the deptarture time of the 3rd route: ";
  std::cin >> dept3;


  std::cout << "\nPlease enter the time you wish to leave: ";
  std::cin >> time2leave;

  if (time2leave < dept1) {
    std::cout << "\nYou should probably take the " << route1 << " that leaves at "
              << dept1 << std::endl;
  } else if ((time2leave <dept2) && (time2leave > dept1)) {
    std::cout << "\nYou should probably take the " << route2 << " that leaves at "
              << dept2 << std::endl;
  } else if ((time2leave <dept3) && (time2leave > dept1) &&
        (time2leave > dept2)) {
    std::cout << "\nYou should probably take the " << route3 << " that leaves at "
              << dept3 << std::endl;
  }
}

1 个答案:

答案 0 :(得分:1)

您的问题是std::cin >> dept1读取数字,但将'\n'留在输入流中。下次阅读std::getline(std::cin, route2);会选取'\n',而不会等待您的输入。