使用C ++中的find语句将罗马数字转换为数字

时间:2013-08-31 14:57:32

标签: c++

您好我在使用C ++将罗马数字转换为普通数字时遇到了问题,但是如果输入数字(XIV 14或LIV等),则代码会在某种程度上起作用,它会输出15或55。 我试图实现find语句,但我不知道如何使用它来解决我的问题,这是我的代码到目前为止的副本;

int convNum;
int total = 0;
string romanNum;
const string units [10]= {"0","I","II","III","IV","V","VI","VII","VIII","IX"};
const string tens [10]= {"0","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
const string hundreds [10]= {"0","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
const string thousands [4]= {"0","M","MM","MMM"};
string input;

while(!cin.eof()){
    cin>>romanNum;
    if(cin.fail()){
        break;
    }else{
        for(int i=0; i<romanNum.length(); i++){
            romanNum[i]=toupper(romanNum[i]);
        }
        for(int y=3; y > 0; y--){
           if(romanNum.find(thousands[y])!= string::npos){
               total += y*1000;
               input.erase(0,thousands[y].length());
               break;
            }
        }
        for(int y=9; y > 0; y--){
           if(romanNum.find(hundreds[y])!= string::npos){
               total += y*100;
               input.erase(0,hundreds[y].length());
               break;
            }
        }
        for(int y=9; y > 0; y--){
           if(romanNum.find(tens[y])!= string::npos){
               total += y*10;
               input.erase(0,tens[y].length());
               break;
            } 
        }
        for(int y=9; y > 0; y--){
           if(romanNum.find(units[y])!= string::npos){
               total += y;
               input.erase(0,units[y].length());
               break;
            }
        }
        cout << total << endl;
        total = 0;
           }

        for(int k=0; k < romanNum.length(); k++){
            input[k] = romanNum[k];
        }


        }     


return 0;

}

如果有人可以帮助我,我将非常感激,因为我是初学者并且编码了这么多的C ++代码花了我大约2周的代码。

2 个答案:

答案 0 :(得分:1)

看起来你有两个问题:

首先,当您删除找到的数字时,您正在删除input字符串,而不是romanNum字符串。您应该从romanNum字符串中删除:

romanNum.erase(0, thousands[y].length());

其次,看起来你在字符串中的任何地方搜索结果,而不仅仅是在开头。所以在“LIV”的例子中,当你在units列表中搜索时,它会在列表的末尾找到“V”,加上5,然后它将删除“I”(因为它总是从列表的前面删除。一个解决方案是只接受当前字符串开头的结果。所以,不要执行!= string::npos,而只需== 0

if (romanNum.find(thousands[y]) == 0) {

答案 1 :(得分:0)

我不会为你做调试,我只会找出三个问题。

  1. 您正在romanNum中搜索,但是您正在删除从input找到的字符。那不应该是同一个字符串吗?

  2. 你得到15,因为在数字中找到的第一个unit字符串是"V",而不是"IV",因为你是以相反的顺序迭代。

  3. 您是否应该寻找前缀的字符串?不在任何地方。您希望find方法返回0,而不是其他任何方法。