我正在用Prata的C++ Primer Plus自学C++,我遇到了一个问题。我在Prata中没有得到任何错误,程序编译成功,但是给了我一个未处理的异常( 0x76ED016E (ntdll.dll) in VS2012 2.5.exe: 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;
}我也不知道我是否万无一失。即。函数中的公式以及开关的顺序。请不要纠正这一点,一旦这该死的东西编译好了,我会自己弄清楚的。:)
发布于 2013-03-15 15:03:10
请参考评论中的经验法则。您正在使用char*,但没有足够的细节知识来正确使用它。使用std::string,它将执行您所需的操作。
供将来参考:使用char*
>F29
对于初学者来说,这是一个很大的挑战。使用std::string。
string convertChoice = "a";别忘了
#include <string>https://stackoverflow.com/questions/15426343
复制相似问题