c++ - 使用单个输入 C++ 在数组中存储多个整数
问题描述
constexpr int SIZE = 500; /* I don't know how to create an array with infinite amount of slots. And it's unreasonable to expect the user to input more than 500 coordinates */
int x_arr[SIZE] = { 0 };
int y_arr[SIZE] = { 0 };
double d = 0.0;
int i = 0;
cout << "Enter the points:" << endl;
while(cin >> d) {
int xy_arr[2] = { 0 };
for(int j = 0; j < 2; j++) {
cin >> xy_arr[j];
}
x_arr[i] = xy_arr[0];
y_arr[i] = xy_arr[1];
i = i + 1;
}
for(int n = 0; n <= i; n++) {
cout << x_arr[n] << y_arr[n] << endl;
}
我希望 xy_array 存储两个整数(x 和 y),即一个坐标。将其视为将整数虹吸到 x_array 和 y_array 的临时数组。
我想要一个 x 坐标和 y 坐标的数组。但是用户必须将 x 坐标和 y 坐标作为单个输入来输入。他们可以输入任意数量的坐标。例如: 输入点数:
5 4
5 6
2 3
4 4
ETC ...
并且在每次迭代后 xy_array 都会重置,因此可以插入新的整数。
我不明白为什么这段代码不起作用。
解决方案
为了完成Max Vollmer的回答,这里有一个在“STOP”命令上停止的解决方案(在对 OP 的评论中询问):
#include <iostream>
#include <sstream>
#include <vector>
struct Coordinate {
int x;
int y;
};
int main() {
std::vector<Coordinate> coordinates;
std::cout << "Enter the points:" << std::endl;
std::string input;
while (std::getline(std::cin, input) && input != "STOP") {
std::istringstream iss;
iss.str(input);
int x, y;
if (iss >> x >> y) {
coordinates.push_back({ x, y });
} else {
std::cout << "Invalid input: " << input << std::endl;
}
}
for (auto coordinate : coordinates) {
std::cout << coordinate.x << ", " << coordinate.y << std::endl;
}
return 0;
}
使用getline将用户输入读取到一个字符串,该字符串首先与“STOP”进行比较,并且只有在失败时(即输入是其他内容,可能是一组坐标),它用于提供两个坐标都可以从中获取的istringstream提取。
推荐阅读
- r - 一旦放入数据框中,日期就会神秘地转换为数字数据
- flutter - Flutter 像画布一样渲染到屏幕上。我如何实现这种布局?
- python - Flask_mail 连接被拒绝
- android - 二进制 XML 文件错误膨胀 RecyclerView
- android - 从设备上卸载我的应用程序使我无法再从 Android Studio 运行它
- javascript - 如何在打字稿中将这些对象转换为数组
- testing - Kotlin 测试类应该是内部的吗?
- spreadsheet - 如何在 Google 电子表格中永久隐藏可旋转的编辑器框?
- three.js - 在 Three.js 点云中显示深度
- laravel - 从所见即所得编辑器呈现值时编译模板意外标识符时出错