2013-05-17 100 views
1

這就是我的程序的工作原理。它提示用戶輸入,一旦檢測到非數字,循環將停止。這裏是我的代碼:cin向C++中的向量

int size = 0; 
float number; 
float total = 0; 
vector <float> data; 

//prompt user to enter file name 
string file; 
cout << "Enter a file name : " ; 
cin >> file ; 
//concatenate the file name as text file 
file += ".txt"; 

//Write file 
cout << "Enter number : "; 
ofstream out_file; 
out_file.open(file); 
while(cin >> number) 
{ 
    data.push_back(number); 
    size++; 
} 

cout<< "Elements in array are : " ; 
//check whether is there any 0 in array else print out the element in array 
for (int count = 0; count < size; count++) 
{ 
    if (data.size() == 0) 
    { 
     cout << "0 digit detected. " << endl; 
     system("PAUSE"); 
    }else 
    { 
     //write the element in array into text file 
     out_file << data.size() << " " ; 
     cout << data.size() << " "; 
    } 
} 
out_file.close(); 

但是,有一些錯誤。例如,我輸入1,2,3,4,5,g,它應該把數組寫成1,2,3,4,5到文本文件中。但是,它用5,5,5,5,5代替。我在想我是否錯誤地使用了push_back?任何指南,將不勝感激。

在此先感謝。

+0

您不需要自己跟蹤大小; 'std :: vector'爲你做。輸出矢量內容的慣用方法是'std :: copy(data.begin(),data.end(),std :: ostream_iterator (out_file,「」));' –

回答

1
for (int count = 0; count < data.size(); count++) { 
    if (data[count] == 0) { 
     cout << "0 digit detected. " << endl; 
     system("PAUSE"); 
    } else { 
     //write the element in array into text file 
     out_file << data[count] << " " ; 
     cout << data[count] << " "; 
    } 
} 
out_file.close(); 

使用元素而不是矢量的大小。例如:

std::vector<int> yourVector; 

yourVector.push_back(1); 
yourVector.push_back(3); 

cout << "My vector size: " << yourVector.size() << endl; //This will give 2 

cout << "My vector element: " << yourVector[0] << endl; //This will give 1 
+0

好吧,我已經知道了。謝謝 – Yvonne

+0

想通過顯示正確的方式來做到這一點將是有用的:) –

+0

雅遐我剛剛感到困惑。 .size就像java中的.length,它只給你數組/矢量的大小。它通過數組循環數據來解決問題。非常感謝 – Yvonne

2

這條線路是你要去哪裏錯了:

out_file << data.size() << " " ; 

您只需插入載體,而不是在條目中的數據的大小...

(事實上你只是檢查data.size()

+0

但是我認爲數據.size()只是獲取整個向量並將其寫入文本文件? – Yvonne

+0

沒有。它返回元素的數量 – Nim

+0

哦好吧,非常感謝 – Yvonne