这是我第一次在这里发帖,如果我做错了,请提前道歉。我正在开展一个项目,其中一部分程序需要翻译电话字(IE“Rad-Code”)到相应的电话号码(IE 723-2633)。我正在尝试使用switch语句以及at()和length()类成员函数。我已经尝试为此部分切换我的代码的顺序,但它一直给我一个错误说明:“输入电话字:Rad-Code 723-2633terminate在抛出'std :: out_of_range'的实例后调用了什么( ):basic_string :: at:__n(8)> = this-> size()(即8)“
以下是相关代码:
int constant = 300;
float begin_x = 0, begin_y = 550, end_x, end_y, control = 1, light = 30; // Light is what I get through the serial port from the Engduino (an Arduino type board`)
PGraphics pg;
void setup()
{
size(10000, 800); // The 10000-pixel wide window.
pg = createGraphics(width, height);
}
void draw()
{
end_x = begin_x + (400 / (sqrt(light) + 1));
end_y = begin_y - constant;
control = end_x - begin_x;
pg.beginDraw();
pg.noFill();
pg.smooth();
pg.strokeWeight(3);
pg.bezier(begin_x, begin_y, begin_x + control, begin_y, end_x - control, end_y, end_x, end_y);
pg.endDraw();
constant = constant * (-1);
begin_x = end_x;
begin_y = end_y;
background(200);
image(pg, -mouseX, 0);
}
答案 0 :(得分:0)
这是您的问题:phoneWord.at(8)
。应该是`phoneWord.at(7)。
这是实现意图的更简洁方式:
// DIGIT_MAP is a static map of characters to digits, 'a' -> 0, 'q' -> 7 etc.
for (auto it = phoneWord.cbegin(); it != phoneWord.cend(); ++it)
cout << DIGIT_MAP[tolower(*it)];
无需使用at
,这就是迭代器的用途。
答案 1 :(得分:0)
如果索引超出范围,您会注意到std::vector::at
会抛出异常:
如果
out_of_range
超出范围,它会抛出n
。
作为@Retired Ninja points out in the comments:您的最终cout
语句在访问元素之前不检查索引
cout << phoneWord << " translates to " << phoneWord.at(0) << phoneWord.at(1) << phoneWord.at(2) << phoneWord.at(3) << phoneWord.at(4) << phoneWord.at(5) << phoneWord.at(6) << phoneWord.at(8) << ".";
最终phoneWord.at(8)
可能是phoneWord.at(7)
,但你可以简化这一点以防止出现这样的问题:
std::cout << phoneWord << " translates to ";
for (auto c : phoneWord)
std::cout << c;
std::cout << "." << std::endl;
这将安全地遍历phoneWord
中的所有值,您无需担心访问超出范围的元素。如果phoneWord