我正在嘗試按列讀取文件。主要功能是我的文件應該顯示列的所有值之一。 我想用矢量做到這一點。按列讀取文本文件並顯示列值的所有數組
void search(){
const int COLUMNS = 4;
vector< vector <int> > data;
string filename = "bla.txt";
ifstream ifile(filename.c_str());
if (ifile.is_open()) {
int num;
vector <int> numbers_in_line;
while (ifile >> num) {
numbers_in_line.push_back(num);
if (numbers_in_line.size() == COLUMNS) {
data.push_back(numbers_in_line);
numbers_in_line.clear();
}
}
}
else {
cerr << "There was an error opening the input file!\n";
exit(1);
}
//now get the column from the 2d vector:
vector <int> column;
int col = 2;//example: the 2nd column
for (int i = 0; i < data.size(); ++i) {
column.push_back(data[i][col - 1]);
cout << column[i] << endl;
}
ifile.close();
}
我的文件看起來像:
John 1990 1.90 1
Peter 1980 1.88 0
...
此代碼編譯,但我沒有得到在控制檯中顯示的任何值。當我嘗試調試最後一行時,它不會被緩存,所以我猜他們什麼都不做?
您打算將'John'和'Peter'存儲在您的'vector'中,而不是ifstream的失敗位置位,您將無法進入循環。然後,因爲'data.size()'等於0,所以沒有任何結果。 –
user
如何使它成爲多種類型的矢量? – NotsoPr0
@ NotsoPr0:這是一個完全不同的問題。因此,您應該在SO上提出一個新問題或搜索現有問題。提示:類似'boost :: any'的東西可能會有所幫助。 –