請幫助除錯。
在第五次輸入后,它給了我一個錯誤“字串下標超出范圍錯誤”。

我無法弄清楚要改變什么。
這是代碼:
#include <iostream>
#include <string>
#define N 100
int str2int(std::string input)
{
int num = 0;
for (int i = 0; i < input.length(); i )
{
if (input[i] == 'V')
num *= 4 0;
else if (input[i] == 'U')
num *= 4 1;
else if (input[i] == 'C')
num *= 4 2;
else if (input[i] == 'D')
num *= 4 3;
}
return num;
}
int main(void)
{
int tablet = 0, num1 = 0, num2 = 0, ans = 0;
std::string cowNum1 = "", cowNum2 = "", result = "";
std::string operation = "";
std::cin >> tablet;
std::cout << "COWCULATIONS OUTPUT" << std::endl;
while (tablet--)
{
std::cin >> cowNum1 >> cowNum2;
num1 = str2int(cowNum1);
num2= str2int(cowNum2);
for (int oprt = 0; oprt < 3; oprt )
{
std::cin >> operation[oprt];
switch (operation[oprt])
{
case 'A':
{
num2 = num1;
break;
}
case 'R':
{
num2 >>= 2;
break;
}
case 'L':
{
num2 <<= 2;
break;
}
case 'N':
default:
break;
}
}
std::cin >> result;
ans = str2int(result);
if (num2 == ans)
std::cout << "YES" << std::endl;
else
std::cout << "NO" << std::endl;
std::cout << "END OF OUTPUT" << std::endl;
}
return 0;
}
問題來自377 - Cowculations
樣本輸入
5
VVVVU
VVVVU
A
A
A
VVVVVVUV
VVCCV
VVDCC
L
R
A
VVVVUCVC
VVCCV
VVDCC
R
L
A
VVVVUCVV
VVUUU
VVVVU
A
N
N
VVVVVUCU
DDDDD
VVVVU
A
L
L
UVVVVVVV
uj5u.com熱心網友回復:
您不能對空字串使用下標運算子來更改其值
std::cin >> operation[oprt];
至少您必須使用 for 回圈中使用的幻數 3 來宣告物件操作。例如
std::string operation( 3, '\0' );
要么
std::string operation;
operation.resize( 3 );
如果您只需要在回圈中輸入一個字符,則std::string不需要該型別的物件。你可以寫
for (int oprt = 0; oprt < 3; oprt )
{
char c;
std::cin >> c;
switch ( c )
{
case 'A':
{
num2 = num1;
break;
}
case 'R':
{
num2 >>= 2;
break;
}
case 'L':
{
num2 <<= 2;
break;
}
case 'N':
default:
break;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/455726.html
下一篇:如何在C#中獲取泰語字串的長度?
