c++user-inputearly-stopping

C++ program stops after user input


#include "util.h"
#include <cmath>

double celsius(double t)
{
    double C = (t-32) * 5/9;
    C = round(C);
    return C;
}

double fahrenheit(double t)
{
    double F = t * 9/5 + 32;
    F = round(F);
    return F;
}

double round(double num)
{
    double rounded = round(num);
    return rounded;
}

int main()
{
    double temp = readDouble("Please enter a temperature: ");
    string type = readLine("Enter C to convert to Celsius or F to convert to Fahrenheit: ");
    if(type == "C")
    {
        double convertedTemp = celsius(temp);
        cout << temp << " degrees Celsius is " << convertedTemp << " degrees Farenheit";
    }
    else if(type == "F")
    {
        double convertedTemp = fahrenheit(temp);
        cout << temp << " degrees Fahrenheit is " << convertedTemp << " degrees Celsius"; 
    }
    
    return 0;
}

This is a program I wrote that converts a temperature from Fahreinheit to Celsius or vice versa. For some reason the program stops running right after the user enters C or F without running the if statements.

I put in print statements all throughout to see if maybe it was running them and just not printing anything but it seems it just stops after "string type = readLine("Enter C to convert to Celsius or F to convert to Fahrenheit: ");" Is there something wrong with my code or is it just the website I'm running it on (CodeHS)? I've looked through similar posts and have tried adding system("pause") or cin << randomVariable right before return 0, but neither worked.


Solution

  • It looks like there's an issue with your round() function. You have a function named round(), which is also the same name as the round() function from the <cmath> library. This can cause a conflict.

    When you call round(C) or round(F) inside your conversion functions, it's recursively calling your round() function instead of the one from the <cmath> library. This leads to a stack overflow, and your program crashes.