MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   在C中找到一堆数组中的max (https://www.labfans.com/bbs/showthread.php?t=26538)

poster 2019-12-14 20:13

在C中找到一堆数组中的max
 
我有几个问题。我有一个包含这些信息的文本文件

x0,x1,y0,y1 142,310,0,959 299,467,0,959 456,639,0,959 628,796,0,959[LIST=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}[*]然后,对于每个c[1]到c[4] ,我想找到最大整数并将其存储在[x,y]数据类型中。因此,例如在c[1] ,最大值将为max[1] = [310,959]。
[/LIST]有人可以帮忙吗?除使用数组解决此问题外,其他C解决方案也将受到欢迎。

在matlab中,代码是

fid = fopen('foo.txt','r'); c = textscan(fid,'%d%d%d%d','delimiter',',','headerlines',1); fclose(fid); 这将仅忽略第一行,然后将其余数字复制到matlab中的数组中。我想将此代码转换为C。非常感谢。



[B]回答:[/B]

尽管没有直接满足您的问题,但我提供了使用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;

[url=https://stackoverflow.com/questions/5239570]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 14:54

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