gpt4 book ai didi

c++ - 满足中断条件后继续循环

转载 作者:行者123 更新时间:2023-12-02 10:11:36 24 4
gpt4 key购买 nike

我目前的作业要求我允许用户传递字符串,并将罗马数字转换为十进制值。我遇到了一个问题,当随机单词通过程序时,它必须返回最长的有效前缀,而忽略其余字符。我的代码通过while循环运行,一旦达到中断条件,它将再次为其余字符重复代码。我不确定下一步应该采取什么步骤来修复此代码以正确输出。下图显示了通过代码传递的字符。
Image of test failure

#include <iostream>
#include <ctype.h>

using namespace std;
int
main (){
while (!cin.eof ()){
char inputChar;
int result = 0;
while (cin.get (inputChar))
{
inputChar = toupper (inputChar);
if (inputChar == 'M')
result = result + 1000;
else if (inputChar == 'D')
{
inputChar = cin.peek ();
inputChar = toupper (inputChar);
if (inputChar == 'M')
{
result = result - 500;
continue;
}
else if (inputChar == 'D'){
result = result;
continue;
}
else
{
result = result + 500;
continue;
}
}
else if (inputChar == 'C')
{
inputChar = cin.peek ();
inputChar = toupper (inputChar);
if (inputChar == 'M' || inputChar == 'D')
{
result = result - 100;
continue;
}
else
{
result = result + 100;
continue;
}
}
else if (inputChar == 'L')
{
inputChar = cin.peek ();
inputChar = toupper (inputChar);
if (inputChar == 'M' || inputChar == 'D' || inputChar == 'C')
{
result = result - 50;
continue;
}
else
{
result = result + 50;
continue;
}
}
else if (inputChar == 'X')
{
inputChar = cin.peek ();
inputChar = toupper (inputChar);
if (inputChar == 'M' || inputChar == 'D' || inputChar == 'C'
|| inputChar == 'L')
{
result = result - 10;
continue;
}
else
{
result = result + 10;
continue;
}
}
else if (inputChar == 'V')
{
inputChar = cin.peek ();
inputChar = toupper (inputChar);
if (inputChar == 'M' || inputChar == 'D' || inputChar == 'C'
|| inputChar == 'L' || inputChar == 'X')
{
result = result - 5;
continue;
}
else
{
result = result + 5;
continue;
}
}
else if (inputChar == 'I')
{
inputChar = cin.peek ();
inputChar = toupper (inputChar);
if (inputChar == 'M' || inputChar == 'D' || inputChar == 'C'
|| inputChar == 'L' || inputChar == 'X' || inputChar == 'V')
{
result = result - 1;
continue;
}
else
{
result = result + 1;
continue;
}
}
else{
break;
}
}
if (result != 0)
{
cout << result << endl;
}
}
return 0;
}

最佳答案

您的break语句不会同时出现在两个while循环中。它只打破内部循环,而不打破外部循环。您可以使用标志告诉外循环不要继续:

int main() 
{
bool exit_loop = false; // define a flag here
while (!cin.eof()) {
char inputChar;
int result = 0;
if (exit_loop) // check the flag here
break;
while (cin.get(inputChar))
{
并在将单位设置为true时:
 }
else
{
exit_loop = true; // set the flag here
break;
}

关于c++ - 满足中断条件后继续循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63336547/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com