【问题标题】:Return values from one of two columns, or skip every other element in an array?从两列之一返回值,还是跳过数组中的所有其他元素?
【发布时间】:2014-01-22 00:14:11
【问题描述】:

我正在尝试编写两个单独的函数,这两个函数都从数据文件中读取,但只返回其中两列之一。 (注释不在.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

如何在一个函数中返回代表“小时”的元素,并在另一个函数中返回“工资率”?

【问题讨论】:

  • 你试过的代码呢?
  • 什么都没试过,不知道怎么弄。
  • 在 StackOverflow 中搜索“c++ 从文件列读取”。
  • 为什么不能用一个函数读取两列?

标签: c++ arrays file


【解决方案1】:

使用 fstreamifstream 对象和提取运算符。

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

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

【讨论】:

    【解决方案2】:
    // "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 也是如此。 同样,如果这确实是您需要的,您可以通过返回相应的向量来“返回一列”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-03
      • 2012-10-30
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多