Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我有几个问题。我有一个包含这些信息的文本文件
x0,x1,y0,y1 142,310,0,959 299,467,0,959 456,639,0,959 628,796,0,959
在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; 更多&回答... |
![]() |
![]() |