-1

I am trying to make a converter between Celsius and Fahrenheit but I have a problem. When I run my code end enter "Celsius to Fahrenheit" it is terminated. Here is my code:

#include <iostream>

int main() {
    std::string ftc;
    int f;
    int c;
    std::cout << "Celsius to Fahrenheit or Fahrenheit to Celcius ";
    std::cin >> ftc;
    if(ftc == "Celsius to Fahrenheit") {
        std::cout << "(c to f) Please provide input ";
        std::cin >> c;
        f = (c*1.8)+32;
        std::cout << f;
    } else if(ftc == "Fahrenheit to Celsius") {
        std::cout << "(f to c) Please provide input ";
        std::cin >> f;
        c = (f-32)*0.5556;
        std::cout << c;
    }
}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
L Jen
  • 33
  • 1
  • 6
  • Use `std::getline` when accepting strings from standard input. Not `std::cin`. – Ron Jan 13 '18 at 19:03
  • @Ron -- you're essentially right, but to clarify, `std::getline` should be applied here to `std::cin`; the problem in the code is not the use of `std::cin`, but the use of `operator>>`. – Pete Becker Jan 13 '18 at 19:34
  • @PeteBecker I agree. – Ron Jan 13 '18 at 19:35
  • 1
    Just a comment on usability: the code should not insist on the user correctly typing "Celsius to Fahrenheit". Just ask for `'C'` or `'c'` or `'F'` or `'f'`. – Pete Becker Jan 13 '18 at 19:35

2 Answers2

0

cin will stop reading into ftc when it encounters white-space, so it will only read one word. Use std::getline() instead. This should work:

#include <iostream>
#include <string>

int main() {
    std::string ftc;
    int f;
    int c;
    std::cout << "Celsius to Fahrenheit or Fahrenheit to Celcius ";
    std::getline(std::cin, ftc);
    if(ftc == "Celsius to Fahrenheit") {
        std::cout << "(c to f) Please provide input ";
        std::cin >> c;
        f = (c*1.8)+32;
        std::cout << f;
    } else if(ftc == "Fahrenheit to Celsius") {
        std::cout << "(f to c) Please provide input ";
        std::cin >> f;
        c = (f-32)*0.5556;
        std::cout << c;
    }
}

Read this for more information: http://www.cplusplus.com/doc/tutorial/basic_io/

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
0

The problem is with

if(ftc == "Celsius to Fahrenheit") try with single word like

if(ftc == "Celsius")

Works! this way