我正在使用Prata的C ++ Primer Plus自学C ++并遇到问题。我在VS2012 Pro中没有出现任何错误并且程序编译成功但是给了我一个未处理的异常(Prata 2.5.exe中0x76ED016E(ntdll.dll)的未处理异常:0x00000000:操作成功完成。)当我尝试进入时C或F作为我的初始选项,我不知道我哪里出错了。练习只要求我创建一个简单的程序,将华氏温度转换为摄氏温度,但我认为我会发现这样的东西很有用,因为我经常使用在线资源来进行这种转换。如果我有自己的程序,我不必担心,可以将其扩展为非CLI版本和更多转换选项(即。码到米等)。任何帮助将不胜感激。
#include "stdafx.h"
#include <iostream>
// Function Prototypes
double convertToF(double);
double convertToC(double);
int main()
{
using namespace std;
char* convertChoice = "a"; // Initializing because the compiler complained. Used to choose between celsius and fahrenheit.
int choiceNumber; // Had issues using the char with switch so created this.
double tempNumber; // The actual temperature the user wishes to convert.
cout << "Do you wish to convert to [C]elcius or [F]ahrenheit?";
cin >> convertChoice;
// IF() compares convertChoice to see if the user selected C for Celsius or F for fahrenheit. Some error catching by using the ELSE. No converting char to lower though in case user enters letter in CAPS.
if (convertChoice == "c")
{
cout << "You chose Celsius. Please enter a temperature in Fahreinheit: " << endl;
cin >> tempNumber;
choiceNumber = 1;
}
else if (convertChoice == "f")
{
cout << "You chose Fahrenheit Please enter a temperature in Celsius: " << endl;
cin >> tempNumber;
choiceNumber = 2;
}
else
{
cout << "You did not choose a valid option." << endl;
}
// SWITCH() grabs the int (choiceNumber) from the IF(), goes through the function and outputs the result. Ugly way of doing it, but trying to make it work before I make it pretty.
switch (choiceNumber)
{
case 1:
double convertedFTemp;
convertedFTemp = convertToC(tempNumber);
cout << convertedFTemp << endl;
break;
case 2:
double convertedCTemp;
convertedCTemp = convertToF(tempNumber);
cout << convertedCTemp << endl;
break;
default:
cout << "You did not choose a valid option." << endl;
break;
}
// To make sure the window doesn't close before viewing the converted temp.
cin.get();
return 0;
}
// Function Definitions
double convertToF(double x)
{
double y;
y = 1.8 * x + 32.0;
return y;
}
double convertToC(double x)
{
double y;
y = x - 32 / 1.8;
return y;
}
我也不知道我是否一切正常。即。函数中的公式以及开关的顺序。请不要纠正这个问题,一旦该死的东西汇编起来,我会为自己解决这个问题。 :)
答案 0 :(得分:3)
请参阅评论中的经验法则。您正在使用char *,但没有足够的细节知识才能正确使用它。使用std :: string,它将完全满足您的需求。
供将来参考:使用char *
这对初学者来说很重要。使用std::string。
string convertChoice = "a";
别忘了
#include <string>