I have made a temperature conversion problem. everything works except for one bit of programming. I am suppose to account for the segmentation fault if someone only enters one command line argument.
correct way to enter: ./a.out 134 F
segmentation fault enter: ./a.out 134
its suppose to display, "You must enter two arguments" but it just displays segmentation fault. It can only be If statements, and the fault is with my first if statement. Heres my program:
Code:
#include <iostream> // cout
#include <cstdlib> // atoi
#include <iomanip> // fixed, setprecision
using namespace std;
int main(int argc, char *argv[]) {
float temp, degrees, F_C, F_K, C_F, C_K, K_C, K_F;
char temp_type;
temp = atoi(argv[1]);
temp_type = *argv[2]; // conversion of temperature type to char
F_C = (temp - 32) * 5/9; // fahrenheit to celsius
F_K = (temp + 459.67) * 5/9; // fahrenheit to kelvin
C_F = temp * 9/5 + 32; // celsius to fahrenheit
C_K = temp + 273.15; // celsius to kelvin
K_C = temp - 273.15; // kelvin to celsius
K_F = temp * 9/5 - 459.67; // kelvin to fahrenheit
cout << fixed << setprecision(1);
if (argc != 3) {
cout << "You must enter two arguments." << endl;
return 1;
}
// displays converted temps of Fahrenheit to celcius and kelvin
if (temp_type == 'F') {
cout << temp << "F is " << F_C << "C and " << F_K << "K" << endl;
}
// displays converted temps of Celcius to fahrenheit to kelvin
if (temp_type == 'C') {
cout << temp << "C is " << C_F << "F and " << C_K << "K" << endl;
}
// displays converted temps of Kelvin to fahrenheit and celsius
if (temp_type == 'K') {
cout << temp << "K is " << K_F << "F and " << K_C << "C" << endl;
}
// displays fault if wrong temperature type is entered
if ((temp_type != 'F') && (temp_type != 'C') && (temp_type != 'K')) {
cout << temp_type << " is not valid temperature type." << endl;
}
cout << "$" << endl;
return 0;
}