0

I'm a super new student learning c++ and created a small currency converter that takes a string for input for a country you are visiting. With the normal std::cin >> country; the program runs fine but won't read countries like "Dominican Republic". I tried using getline but that skips over the country input straight to the last else {} statement.

    std::cout << "Enter how many US Dollars you want to convert: " << std::endl;
    std::cin >> USD;

    std::cout << "What country are you planning to visit?" << std::endl;
    std::getline(std::cin, country);


    if (country == "Canada") {
        conversion = USD * 1.2074;
        std::cout << USD << " US dollars converted into Canadian Dollars (CAD) is: " << std::endl;
        std::cout << conversion << " Canadian Dollars" << std::endl;
        std::cout << "Hit Y if you'd like to convert again or N to quit. " << std::endl;
        std::cin >> again;
    }
    else {
        std::cout << "Sorry, this converter only has major US tourist destinations." << std::endl;
        std::cout << "Please try another country. Hit Y if you'd like to try again or N to quit.";
        std::cin >> again;
    }

How can I adjust the code to actually receive the input before running the else branch? Thank you guys!

dkeys
  • 1
  • 2
  • When you mix `std::cin >>` that leaves the `'\n'` unread in `stdin` and `getline()` that reads up until the first `'\n'` is encountered you can see that calling `std::cin >>` before `getline()` will result in `getline()` seeing the `'\n'` as the first character to read -- and reading nothing... See [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction?r=SearchResults&s=3|142.1224) – David C. Rankin May 30 '21 at 02:04
  • [std::basic_istream::ignore](https://en.cppreference.com/w/cpp/io/basic_istream/ignore) is your friend. – David C. Rankin May 30 '21 at 02:09
  • @davidc.Rankin thank you so much! The std::cin.ignore(); fixed it. I have learned something new so thank you so much! – dkeys Jun 01 '21 at 21:30
  • Glad to help. Any day you can learn something new -- it's a good day. Remember, education is nothing more than a slow revelation of the truth that lasts a lifetime... (if you are living right `:)` – David C. Rankin Jun 01 '21 at 22:41

0 Answers0