0

我正在使用 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;
}

我也不知道我是否一切都正确。IE。函数中的公式以及开关的顺序。请不要纠正,一旦该死的东西编译,我会自己弄清楚。:)

4

1 回答 1

3

请参考评论中的经验法则。您在使用 char* 时没有足够的细节知识来正确使用它。使用 std::string,它将完全满足您的需求。

供将来参考:使用 char*

  • 你需要分配内存
  • 您需要使用 strcmp 进行比较
  • 你需要自己看长度
  • 你需要释放内存

这对于初学者来说很多。使用std::string

string convertChoice = "a";

不要忘记

#include <string>
于 2013-03-15T07:03:10.343 回答