0

I'm writing code that consists of the user inputting a bus route and the time it departs. I am trying to use the std::getline() function so if a user inputs a space it will output correctly. However, I try to compile my code and everything runs smoothly until it reaches the 2nd question of the bus route

heres a photo of it running

here is my code to see, if anyone knows if the getline is a problem or something else:

#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;
  }
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
  • What happens when "it" reaches the second question of the bus route? (No, I am not going to follow a link to get the answer. Questions are supposed to be self-contained, or at least self-contained enough to be understood without following external links. See [ask].) – JaMiT Sep 19 '19 at 02:48

1 Answers1

1

Your problem is that std::cin >> dept1 reads the number but leaves '\n' in the input stream. Next read std::getline(std::cin, route2); picks up that '\n' and does not wait for your input.

Eugene
  • 4,579
  • 1
  • 16
  • 29