0

バグが多いので、誰かが私のコードを変更できることを願っています。うまくいくときもあれば、うまくいかないときもある..

もっと説明させてください.. テキストファイルのデータは以下の通りです

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 であると考えてください。

4

1 に答える 1

0

このコードがクラッシュする理由を説明できません。おそらく、ここに投稿していないバグがあるためです。しかし、このように 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;

}

ダミーの char 変数 (c1、c2 など) を使用して、関心のないコンマとブラケットを読み取ります。この手法は、関心のないスペースもスキップします。これは、ignore を使用するよりもはるかに現実的な方法です。

コード内のその他のエラーは、notoperator>>を使用する必要があり、最後にある必要があります。使用するように記述することで、ファイル ストリームだけでなく、あらゆる種類の入力ストリーム (たとえばを含む) で機能します。istreamifstreamreturn input;operator>>istreamcin

于 2012-11-15T16:57:57.860 に答える