c++ - 在C中的一堆数组中找到最大值

标签 c++ arrays matlab scanf

我有几个问题。 我有一个包含这些信息的文本文件

x0,x1,y0,y1
142,310,0,959
299,467,0,959
456,639,0,959
628,796,0,959
  1. 首先,我想使用 fscanf 读取文本文件并只将数字放入 4 个数组中,c1c2c3c4 跳过第一行。所以最后的结果会是

    c[1] = {142, 310, 0, 959}
    c[2] = {299, 467, 0, 959}
    c[3] = {456, 639, 0, 959}
    c[4] = {628, 796, 0, 959}
    
  2. 然后,对于每个 c[1]c[4],我想找到最大整数并将其存储在 [x, y] 中数据类型。因此,例如在 c[1] 中,最大值将为 max[1] = [310, 959]。

有人可以帮忙吗?也欢迎使用数组以外的其他 C 解决方案来解决此问题。

在matlab中,代码为

fid = fopen('foo.txt','r');
c = textscan(fid,'%d%d%d%d','delimiter',',','headerlines',1);
fclose(fid);

这将简单地忽略第一行,然后将其余数字复制到 matlab 中的数组中。 我想将这段代码翻译成 C。 非常感谢。

最佳答案

虽然没有直接满足您的问题,但我提供了一个使用 struct 读取点的示例, std::istreamstd::vector .这些优于 fscanf和数组。

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 structure 提供了更多的可读性和恕我直言,更多的通用性,因为您可以使用 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>> 添加读取文件的方法对于点:

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 、类或结构到数组。

此外,由于 std::istream使用,这些结构和类可以很容易地与std::cin一起使用和文件(std::ifstream):

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

关于c++ - 在C中的一堆数组中找到最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239570/

相关文章:

matlab - 更改 MATLAB 对话框的字体

c++ - 是否可以使用 Visual Studio 调试 OpenGL 着色器?

c++ - 检查单选按钮状态 winapi

java - 将数组的所有元素向右移动

java GUI分配数组值

ruby - 为什么我不能在 Ruby 中递归地附加到数组的末尾?

macos - Matlab命令行-某些程序在退出时崩溃

matlab - 如何提取表的列名?

c# - SQLite in 10 UWP App Assertion Error (p->iForeGuard==(int)FOREGUARD);

c++ - 在 C++03 中模拟 =delete 以限制复制/赋值操作的最简单方法是什么?