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

Converting roman numerals into numbers using find statement in C++

本文关键字:数字 罗马 转换 语句 find C++      更新时间:2023-10-16

嗨,我在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周的时间。

看起来您有两个问题:

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

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

其次,看起来您正在字符串中的任何位置搜索结果,而不仅仅是在开头。所以在"LIV"的例子中,当你在units列表中搜索时,它会在列表的末尾找到"V",加上5,然后它会擦除"I"(因为它总是从列表的前面擦除。解决这个问题的一个方法是只接受当前字符串开头的结果。所以,不要做!= string::npos,只做== 0:

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

我不为您做调试,我只确定三个问题。

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

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

  3. 你不应该寻找是你的号码前缀的字符串吗?没有任何内容。您希望find方法返回0,而不是其他任何内容。