我有几个问题。 我有一个包含这些信息的文本文件
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 >> 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/