首页 > 解决方案 > 使用单个输入 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 都会重置,因此可以插入新的整数。

我不明白为什么这段代码不起作用。

标签: c++

解决方案


为了完成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提取。


推荐阅读