Visual Studio中abort()调用错误:坐标计算程序多次运行异常求助
C++程序重复运行触发abort()错误的原因与修复
错误根源
- 空字符串越界访问:当用户按下回车输入空行时,
std::getline读取到空字符串,此时直接访问Input[0]会触发未定义行为,最终导致程序调用abort()。 - 输入解析无错误处理:当输入格式不符合要求(空行、空格数量不足、非数字字符)时,
Input.find(' ')会返回std::string::npos,后续调用std::stof处理空字符串或无效内容时,会抛出未捕获的std::invalid_argument或std::out_of_range异常,未捕获的异常会触发程序终止并调用abort()。
修复方案
1. 修正循环条件与空输入处理
修改main函数的循环逻辑,先检查输入是否为空,再判断退出条件,同时添加异常捕获避免程序崩溃:
int main() { // loop while there's more input std::string Input; while (std::getline(std::cin, Input)) { if (Input.empty()) { // 跳过空输入,可按需添加提示信息 continue; } if (Input[0] == 'q') { break; } try { // extract point coordinates from string GetInputValuesFromString(Input); // 计算逻辑 float deltaX{ Point2X - Point1X }; float deltaY{ Point2Y - Point1Y }; float hypo{ sqrtf(deltaX*deltaX + deltaY*deltaY) }; // 替代powf提升效率 float a{ atan2(deltaY, deltaX) }; a = a * 180 / M_PI; std::cout << hypo << " " << a << std::endl; // 添加endl刷新输出缓冲 } catch (const std::exception& e) { std::cerr << "错误:" << e.what() << std::endl; } } }
2. 为输入解析函数添加错误检查
修改GetInputValuesFromString函数,在每一步解析前检查分隔符是否存在,避免无效的字符串处理:
void GetInputValuesFromString(std::string Input) { // extract point 1 x size_t SpaceIndex = Input.find(' '); if (SpaceIndex == std::string::npos) { throw std::invalid_argument("输入格式错误:缺少足够的空格分隔符"); } Point1X = std::stof(Input.substr(0, SpaceIndex)); // move along string and extract point 1 y Input = Input.substr(SpaceIndex + 1); SpaceIndex = Input.find(' '); if (SpaceIndex == std::string::npos) { throw std::invalid_argument("输入格式错误:缺少足够的空格分隔符"); } Point1Y = std::stof(Input.substr(0, SpaceIndex)); // move along string and extract point 2 x Input = Input.substr(SpaceIndex + 1); SpaceIndex = Input.find(' '); if (SpaceIndex == std::string::npos) { throw std::invalid_argument("输入格式错误:缺少足够的空格分隔符"); } Point2X = std::stof(Input.substr(0, SpaceIndex)); // point 2 y is the rest of the string Input = Input.substr(SpaceIndex + 1); if (Input.empty()) { throw std::invalid_argument("输入格式错误:缺少第四个坐标值"); } Point2Y = std::stof(Input); }
额外优化建议
- 将全局变量
Point1X、Point1Y等改为main函数内的局部变量,避免全局状态带来的潜在问题。 - 用
deltaX*deltaX替代powf(deltaX,2),提升计算效率同时避免浮点数幂运算的精度损失。
内容的提问来源于stack exchange,提问作者Chethan R
相关产品推荐
相关产品推荐

