我有几个问题。我有一个包含这些信息的文本文件
x0,x1,y0,y1 142,310,0,959 299,467,0,959 456,639,0,959 628,796,0,959
- 首先,我想使用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]。
有人可以帮忙吗?除使用数组解决此问题外,其他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;
更多&回答...