2012-11-15 40 views
0

是我的代碼C++插播廣告超載問題

ifstream& operator>>(ifstream &input,Line3D &line3d) 
{ 
int x1,y1,z1,x2,y2,z2; 
x1=0; 
y1=0; 
z1=0; 

x2=0; 
y2=0; 
z2=0; 

//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); 


//cout << x1 << "," << y1 << "," << z1 << "," <<endl; 
//cout << x2 << "," << y2 << "," << z2 << "," <<endl; 


Point3D pt1(x1,y1,z1); 
Point3D pt2(x2,y2,z2); 

line3d.setPt1(pt1); 
line3d.setPt2(pt2); 

line3d.setLength(); 
} 

有這個奇怪的問題,如果我的評論我的清點,上述2 COUT。我的代碼將無法正常工作,但如果我取消它,代碼將工作..繼承人的終端輸出..

Please enter your choice: 1 

Please enter filename: messy.txt 
10 records read in successfully! 
Going back to main menu ... 

但是,如果我去掉COUT ...

請輸入您的選擇:1

Please enter filename: file.txt 
7,12,3, 
-9,13,68, 
7,-12,3, 
9,13,68, 
70,-120,-3, 
-29,1,268, 
25,-69,-33, 
-2,-41,58, 
9 records read in successfully! 
Going back to main menu ... 

9記錄是正確的。但爲什麼cout會解決我的代碼問題。而我認爲cout只是打印到終端。我在這裏做錯了什麼。

這是文本文件內容

Point2D, [3, 2] 
Line3D, [7, 12, 3], [-9, 13, 68] 
Point3D, [1, 3, 8] 
Line2D, [5, 7], [3, 8] 
Point2D, [3, 2] 
Line3D, [7, -12, 3], [9, 13, 68] 
Point3D, [6, 9, 5] 
Point2D, [2, 2] 
Line3D, [70, -120, -3], [-29, 1, 268] 
Line3D, [25, -69, -33], [-2, -41, 58] 
Point3D, [6, 9, -50] 

正確的迴應,我從終端要的是

Correct output: 9 records read in successfully 
Reason: as 10 means the value fail to record to vector. and duplicate is not removed. 

感謝所有指南,我應該怎麼做才能保持正確的輸出還刪除掉cout ..

我在main.cpp上的更多代碼:

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,25,','); 

Line3D line3d_tmp; 
readFile>>line3d_tmp; 

done=true; 

//some for loop to check for duplication 
//done will be false if doesnt work 

if(done==true) 
{ 
line3d.push_back(line3d_tmp); 

} 

所以你看看,如果值是push_back到我的向量中,重複的記錄將被刪除,因爲我故意放2個相同的值的記錄。問題是如果我使用2 cout線。記錄顯示爲9(正確,因爲有1行重複),第二次運行輸入相同的文件。正在讀取0條記錄。

但是,如果我在第二次運行時將我的cout註釋掉,它會再次讀取4個記錄。第一次運行爲10條..

+1

請縮小範圍。 –

+0

爲什麼9是正確的?我在你的產量中只看到8行。 –

回答

1

幾點:

  • 變化ifstreamistream
  • 在操作的末端返回input
  • 定義爲operator>>()Point3D使用,在Line3D
+0

我做了point3d,只是不在這裏包含代碼。我的問題是爲什麼會cout解決我的問題,但沒有cout,代碼失敗。這是一個非常奇怪的情況,我遇到了類似於point2d,point3d,line2d的其他類的問題,但只有line3d – user1578897

+0

只是瘋狂的猜測,它是否會改變,當你用'\ n替換'endl'時'? –