C++中从被调用函数向调用函数返回struct的正确方式是什么?
完善你的C++函数:输入验证与结构体返回
我来帮你搞定这个函数,让它能正确处理整数输入、验证有效性,最后用结构体返回结果。先看完整的实现方案:
第一步:定义返回用的结构体
首先我们需要明确要返回的结构体类型,用来封装两个int值,这样调用者能清晰获取结果:
#include <iostream> #include <limits> // 用于清除输入缓冲区的无效字符 // 定义结构体,存储处理后的坐标值 struct Coordinates { int x; int y; };
第二步:完善带输入验证的函数
你原来的代码里输入验证的循环没写完,这里补全逻辑——当用户输入非整数时,要清除错误状态并清空缓冲区,避免陷入死循环:
Coordinates start_end() { int xd = 0; int yd = 0; // 读取并验证X坐标 std::cout << "Please enter a desired x coordinate: " << std::endl; std::cin >> xd; while (std::cin.fail()) { std::cout << "That is not a valid integer. Please enter a valid x coordinate: " << std::endl; std::cin.clear(); // 清除cin的错误状态标志 // 忽略缓冲区中所有无效字符直到换行符 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> xd; } // 读取并验证Y坐标,逻辑和X一致 std::cout << "Please enter a desired y coordinate: " << std::endl; std::cin >> yd; while (std::cin.fail()) { std::cout << "That is not a valid integer. Please enter a valid y coordinate: " << std::endl; std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cin >> yd; } // 用列表初始化返回结构体实例 return {xd, yd}; }
第三步:调用函数并使用结果
在主函数里调用这个函数,就能拿到处理后的结构体了:
int main() { Coordinates user_coords = start_end(); std::cout << "You entered valid coordinates: x = " << user_coords.x << ", y = " << user_coords.y << std::endl; return 0; }
如果你需要函数接收两个int参数(而非从输入读取)
如果你的需求是函数接收外部传入的两个int值,再处理后返回结构体,可以这样修改函数:
// 接收两个int参数,处理后返回结构体 Coordinates start_end(int input_x, int input_y) { // 这里可以添加自定义处理逻辑,比如范围修正、数值计算等 Coordinates processed; processed.x = input_x * 2; // 示例:将X值翻倍 processed.y = input_y + 10; // 示例:将Y值加10 return processed; }
调用示例:
int main() { int x = 15, y = 25; Coordinates result = start_end(x, y); std::cout << "Processed coordinates: x = " << result.x << ", y = " << result.y << std::endl; return 0; }
关键注意点
- 输入验证时,
std::cin.clear()和std::cin.ignore()缺一不可:前者清除错误状态,后者清空缓冲区的无效输入,否则会无限循环读取错误内容。 - 显式声明函数返回类型为
Coordinates比用auto更易读,当然如果结构体定义在函数之前,auto也能正确推导返回类型,但显式类型更清晰。
内容的提问来源于stack exchange,提问作者Arun Kumar
相关产品推荐
相关产品推荐

