简体   繁体   English

C ++程序错误

[英]Error with C++ Program

I am currently taking a C++ class, so bear with me. 我目前正在参加C ++课程,所以请耐心等待。 I am not asking for you to solve my homework, but just simply help me figure out what I am overlooking I am converting Roman numerals that the user inputs into a decimal number and then displaying the number. 我并不是要您解决我的作业,而只是帮助我弄清楚我所忽略的是什么,我正在将用户输入的罗马数字转换为十进制数字,然后显示该数字。 I have not completed my function for conversion yet. 我尚未完成转换功能。 For now, I just convert the numeral into a number and add them up (Not taking into account on the order yet). 现在,我只是将数字转换为数字并加起来(尚未考虑订单上的内容)。 I keep getting a 0 and not the right number whenever I run the program. 每当我运行程序时,我总是得到0,而不是正确的数字。 Here is my code for the header file: 这是我的头文件代码:

class romanType
    {
    public:
        void setNumeral(string);
        string getNumeral();
        double convertToNumber();
        double printNumber();
    private:
        string input;
        double num;
    };

void romanType::setNumeral(string s)
{
    string input = s;
}

string romanType::getNumeral()
{
    return input;
}

double romanType::convertToNumber()
{
    num = 0;
    for(int i = 0; i < input.length(); i++)
    {
        switch (input.at(i))
        {
        case 'M':
            num += 1000;
            break;
        case 'D':
            num += 500;
            break;
        case 'C':
            num += 100;
            break;
        case 'L':
            num += 50;
            break;
        case 'X':
            num += 10;
            break;
        case 'V':
            num += 5;
            break;
        case 'I':
            num += 1;
            break;
        }
    }
    return num;
}

double romanType::printNumber()
{
    return num;
}

Here is my cpp file code: 这是我的cpp文件代码:

#include "stdafx.h"
#include "romanType.h"
#include <string>
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    romanType roman;
    string input;
    string output;
    double number = 0;
    cout << "Enter a Roman numeral." << endl;
    cin >> input;
    roman.setNumeral(input);
    number = roman.convertToNumber();
    cout << number << endl;

    system("pause");
    return 0;
}

In your romanType::setNumeral() remove the "string" word before input : 在您的romanType :: setNumeral()中,在输入之前删除“字符串”一词:

wrong : 错误的:

 romanType::setNumeral(string s)
 {
      string input=s;
 }

right : 对 :

romanType::setNumeral(string s)
{
    input=s;
}

In the wrong example you are hiding your member variable with a local variable with the same name. 在错误的示例中,您使用相同名称的局部变量隐藏了成员变量。

In here: 在这里:

void romanType::setNumeral(string s)
{
    string input = s;
}

Use the field name instead of a local variable 'input' that eclipses the name of the field in this class. 使用字段名称,而不是使此类中的字段名称黯然失色的局部变量“ input”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM