简体   繁体   中英

Error with C++ Program

I am currently taking a C++ class, so bear with me. 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. 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:

#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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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