从两列中的一列返回值,还是跳过数组中的每个其他元素?

时间:2014-01-22 00:14:12

标签: c++ arrays file

我试图编写两个单独的函数,这两个函数都从数据文件中读取,但只从它返回两列中的一列。 (评论不在.dat文件中,只是为了澄清而写的)

//  Hours     Pay Rate
    40.0       10.00
    38.5        9.50
    16.0        7.50
    42.5        8.25
    22.5        9.50
    40.0        8.00
    38.0        8.00
    40.0        9.00
    44.0       11.75

如何返回代表'小时'在一个功能,并返回支付率'在另一个功能?

2 个答案:

答案 0 :(得分:0)

使用 fstream ifstream 对象和提取运算符。

std::ifstream fin(YourFilenameHere);
double hours, rate;
fin >> hours >> rate;

这些对象的类位于fstream标题中。

答案 1 :(得分:0)

// "hours" and "payRate" might as well be class members, depending
// on your design.
vector<float> hours;
vector<float> payRate;
std::ifstream in(fileName.c_str());
string line;
while (std::getline(in, line)) {
  // Assuming they are separated in the file by a tab, this is not clear from your question.
  size_t indexOfTab = line.find('\t');
  hours.push_back(atof(line.substr(0. indexOfTab).c_str());
  payRate.push_back(atof(line.substr(indexOfTab +1).c_str()));
}

现在您可以按小时[i]访问第i个条目,同样适用于payRate。 同样,如果这是你真正需要的,你可以通过返回相应的向量来“返回一列”。