C++ C++;关于cin.ignore()
我希望有人能修改我的代码,因为它有很多错误。有时是工作,有时不是 让我再解释一下。。文本文件数据如下所示C++ C++;关于cin.ignore(),c++,C++,我希望有人能修改我的代码,因为它有很多错误。有时是工作,有时不是 让我再解释一下。。文本文件数据如下所示 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); readFil
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...
但问题是,唱片有时会出问题,有时不会。。我的意思是如果在这一点上
//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();
//我添加了一个cout
我无法解释为什么这个代码会崩溃。这可能是因为你有一些bug没有在这里发布。但是,您会发现用这种方式编写运算符>>更容易
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更可靠的方法
代码中的其他错误是运算符>>
应该使用istream
而不是ifstream
,并且应该具有返回输入代码>在末尾。通过编写操作符>>
来使用istream
,它将处理任何类型的输入流(包括cin
),而不仅仅是文件流
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;
}