更新时间:2023-02-26 18:30:57
尽管没有直接满足您的问题,但我提供了使用struct
,std::istream
和std::vector
的阅读要点示例.这些优先于fscanf
和数组.
Although not satsifying your question directly, I have provided an example of reading points using a struct
, std::istream
and std::vector
. These are preferred over fscanf
and arrays.
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
声明其他类,所以Point
结构提供了更高的可读性,恕我直言,还具有更多的通用性:
The Point
structure provides more readability, and IMHO, more versatility because you can declare other classes using a 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>>
来添加用于读取文件的方法:
You can add methods for reading from a file using the operator>>
for point:
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
,类或结构.
Arrays are a problem and can lead to nasty runtime errors such as buffer overruns. Perfer std::vector
, classes or structures to arrays.
此外,由于使用了std::istream
,因此这些结构和类可以轻松地用于std::cin
和文件(std::ifstream
):
Also, since std::istream
is used, these structures and classes can be easily used with std::cin
and files (std::ifstream
):
// Input from console
Rectangle r;
std::cin >> r;