Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-14, 20:13   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 在C中找到一堆数组中的max

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

x0,x1,y0,y1 142,310,0,959 299,467,0,959 456,639,0,959 628,796,0,959
  1. 首先,我想使用fscanf读取文本文件,并通过跳过第一行将数字仅分为4个数组c1 , c2 , c3和c4 。所以最终结果将是

    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::istream和std::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 >> px; //Insert code here to read the separator character(s) inp >> py; return inp; } void Read_Points(std::istream& input, std::vector& 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声明其他类:

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;

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 15:08


Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.