为了完全解决这个问题,我发布了最终且正确的代码,因为我相信其他人将来也会有同样的问题,我希望这对他们有所帮助。为了回答我的问题,在编写模板时,整个算法需要包含在头文件中,并且不能在头文件和实现文件之间拆分。该程序旨在成为一种从输入文件中读取列数据的非常通用的方法,并假设每列数据的长度与其他列相同。用户只需将头文件添加到他们的主程序中,在向量定义中指定每一列的数据类型并读入数据。主程序如下所示。此版本允许用户调用 4 个不同的函数,这些函数可用于读取多达四列数据。
#include <vector>
#include <iostream>
#include <cstring>
#include "Read_Columnar_File.h"
int main(int argc, const char * argv[]) {
char str[20];
strcpy(str,"Test.txt");
// - Format for reading in a single column of data
// Data in this case is declared as a float in
// the vector, but it can be any data type
/*
std::vector<float> str2;
Read_One_Column(str,str2);
*/
// - Format for reading in two columns of data from
// an input file
/*
std::vector<float> str2;
std::vector<int> str3;
Read_Two_Columns(str,str2,str3);
*/
// - Format for reading in three columns of data from
// an input file
/*
std::vector<float> str2;
std::vector<int> str3;
std::vector<int> str4;
Read_Three_Columns(str,str2,str3,str4);
*/
std::vector<float> str2;
std::vector<int> str3;
std::vector<int> str4;
std::vector<float> str5;
Read_Four_Columns(str,str2,str3,str4,str5);
return 0;
}
The implementation file is shown below.
#include <vector>
#include <stdio.h>
#include <fstream>
#include <iterator>
template <class X> void Read_One_Column(const std::string& file_name,std::vector<X>& Column1)
{
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
std::istream_iterator<X> start((inp)), end;
if(inp.is_open()) {
Column1.assign(start,end);
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
template <class X,class Y> void Read_Two_Columns(const std::string& file_name,std::vector<X>& Column1,
std::vector<Y>& Column2)
{
int i;
X Col1;
Y Col2;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()){
for(i=0; i < 7; i++){
inp >> Col1 >> Col2;
Column1.push_back(Col1), Column2.push_back(Col2);
}
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
template <class X,class Y, class Z> void Read_Three_Columns(const std::string& file_name,std::vector<X>& Column1,
std::vector<Y>& Column2,std::vector<Z>& Column3
{
int i;
X Col1;
Y Col2;
Z Col3;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()){
for(i=0; i < 7; i++){
inp >> Col1 >> Col2 >> Col3;
Column1.push_back(Col1), Column2.push_back(Col2), Column3.push_back(Col3);
}
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
template <class X,class Y, class Z,class A> void Read_Four_Columns(const std::string& file_name,std::vector<X>& Column1,
std::vector<Y>& Column2,std::vector<Z>& Column3,
std::vector<A>& Column4)
{
int i;
X Col1;
Y Col2;
Z Col3;
A Col4;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()){
for(i=0; i < 7; i++){
inp >> Col1 >> Col2 >> Col3 >> Col4;
Column1.push_back(Col1), Column2.push_back(Col2),
Column3.push_back(Col3), Column4.push_back(Col4);
}
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}