文本文件例如包含15列数据,但只有三列(列)对于进一步计算很重要。现在我想通过 ifstream 读取所有列,然后创建一个只包含重要列的新文件(在本例中为3)。
std::vector<double> column1;
std::vector<double> column2;
std::vector<double> column3;
double col1;
double col2;
double col3;
double sortCol1;
double sortCol2;
double sortCol3;
void readingFile()
{
// at very first the user is able to see the data of the file and decide which columns are needed.
std::cout << "Which columns do you need?" << std::endl;
std::cin >> col1; // for example column 3
std::cin >> col2; // column 5
std::cin >> col3; // and column 9
std::ifstream file("testFile.txt"); //reading the file
if(!file)
{
std::cerr << "* Can't open file! *" << std::endl;
}
else
{ // this is the point which i don't get.
// How do i specify "dynamic" which column i need?
// somethimes i need to pushback sortCol7 to column1 sometimes sortCol3 to column1 and so on.
while(file >> sortCol1 >> sortCol2 >> sortCol3 ... and so on...)
{
// i think i need an if-statement here with conditions like:
// col x = sortCol x
column1.push_back(sortCol1);
column2.push_back(sortCol2);
column3.push_back(sortCol3);
}
}
file.close();
}
重要的是要知道数据文件的格式是可变的。所以我不能写一个静态代码,每次在同一个向量中推送相同的列。