[英]C++ Regarding cin.ignore()
我希望有人可以修改我的代码,因为它有很多错误。 有时它的工作,有时它不..
所以让我解释更多..文本文件数据如下
Line3D, [70, -120, -3], [-29, 1, 268]
Line3D, [25, -69, -33], [-2, -41, 58]
阅读上面的行..我使用以下
char buffer[30];
cout << "Please enter filename: ";
cin.ignore();
getline(cin,filename);
readFile.open(filename.c_str());
//if successfully open
if(readFile.is_open())
{
//record counter set to 0
numberOfRecords = 0;
while(readFile.good())
{
//input stream get line by line
readFile.getline(buffer,20,',');
if(strstr(buffer,"Point3D"))
{
Point3D point3d_tmp;
readFile>>point3d_tmp;
// and so on...
然后我在Line3d的ifstream上进行了重载
ifstream& operator>>(ifstream &input,Line3D &line3d)
{
int x1,y1,z1,x2,y2,z2;
//get x1
input.ignore(2);
input>>x1;
//get y1
input.ignore();
input>>y1;
//get z1
input.ignore();
input>>z1;
//get x2
input.ignore(4);
input>>x2;
//get y2
input.ignore();
input>>y2;
//get z2
input.ignore();
input>>z2;
input.ignore(2);
Point3D pt1(x1,y1,z1);
Point3D pt2(x2,y2,z2);
line3d.setPt1(pt1);
line3d.setPt2(pt2);
line3d.setLength();
}
但是问题是记录工作有时是不这样做的..我的意思是,如果此时
//i add a cout
cout << x1 << y1 << z1;
cout << x2 << y2 << z2;
//its works!
Point3D pt1(x1,y1,z1);
Point3D pt2(x2,y2,z2);
line3d.setPt1(pt1);
line3d.setPt2(pt2);
line3d.setLength();
但是,如果我拿走了球囊,它是行不通的。 我如何更改cin.ignore()以便可以正确处理数据,请考虑数字范围为-999至999
我无法解释为什么此代码崩溃。 可能是因为您有尚未在此处发布的错误。 但是,您会发现以这种方式编写operator >>更容易。
istream& operator>>(istream &input,Line3D &line3d)
{
int x1,y1,z1,x2,y2,z2;
char c1,c2,c3,c4,c5,c6,c7;
input >> c1 >> x1 >> c2 >> y1 >> c3 >> z1 >> c4 >> c5 >> x2 >> c6 >> y2 >> c7 >> z2;
Point3D pt1(x1,y1,z1);
Point3D pt2(x2,y2,z2);
line3d.setPt1(pt1);
line3d.setPt2(pt2);
line3d.setLength();
return input;
}
使用哑字符变量(c1,c2等)读取您不感兴趣的逗号和括号。此技术还将跳过您不感兴趣的空格。与使用ignore相比,这是一种更实用的方法。
代码中的其他错误是, operator>>
应该使用istream
而不是ifstream
,并且应该具有return input;
在末尾。 通过编写operator>>
以使用istream
,它将可以与任何类型的输入流(例如,包括cin
)一起使用,而不仅仅是文件流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.