简体   繁体   中英

Return values from one of two columns, or skip every other element in an array?

I'm trying to write two separate functions, both of which read from a data file, but return only one of two columns from it. (The comment isn't in the .dat file, it's just written for clarification)

//  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

How do I return the elements representing 'hours' in one function, and return 'pay rate' in another function?

Use an fstream or ifstream object and the extraction operator.

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

The classes for these objects are in the fstream header.

// "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()));
}

Now you can access the i'th entry in hours by hours[i], same for payRate. Likewise you can "return one column" by returning the corresponding vector if this is really what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM