且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C中找到一堆数组中的max

更新时间:2023-02-26 18:30:57

尽管没有直接满足您的问题,但我提供了使用structstd::istreamstd::vector的阅读要点示例.这些优先于fscanf和数组.

Although not satsifying your question directly, I have provided an example of reading points using a struct, std::istream and std::vector. These are preferred over fscanf and arrays.

struct Point
{
  unsigned int x;
  unsigned int y;

  friend std::istream& operator>>(std::istream& inp, Point& p);
};

std::istream& operator>>(std::istream& inp, Point& p)
{
  inp >> p.x;
  //Insert code here to read the separator character(s)
  inp >> p.y;
  return inp;
}

void Read_Points(std::istream& input, std::vector<Point>& container)
{
  // Ignore the first line.
  inp.ignore(1024, '\n');

  // Read in the points
  Point p;
  while (inp >> p)
  {
     container.push_back(p);
  }
  return;
}

由于您可以使用Point声明其他类,所以Point结构提供了更高的可读性,恕我直言,还具有更多的通用性:

The Point structure provides more readability, and IMHO, more versatility because you can declare other classes using a Point:

class Line
{
  Point start;
  Point end;
};

class Rectangle
{
  Point upper_left_corner;
  Point lower_right_corner;
  friend std::istream& operator>>(std::istream& inp, Rectangle& r);
};

您可以使用operator>>来添加用于读取文件的方法:

You can add methods for reading from a file using the operator>> for point:

std::istream& operator>> (std::istream& input, Rectangle& r)
{
  inp >> r.upper_left_corner;
  //Insert code here to read the separator character(s)
  inp >> r.lower_left_corner;
  return inp;
}

数组是一个问题,可能导致讨厌的运行时错误,例如缓冲区溢出.对数组执行std::vector,类或结构.

Arrays are a problem and can lead to nasty runtime errors such as buffer overruns. Perfer std::vector, classes or structures to arrays.

此外,由于使用了std::istream,因此这些结构和类可以轻松地用于std::cin和文件(std::ifstream):

Also, since std::istream is used, these structures and classes can be easily used with std::cin and files (std::ifstream):

  // Input from console
  Rectangle r;
  std::cin >> r;