2014-01-22 52 views
0

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

如何返回一个代表“小时”在一个函数在其他功能,和返回的工资率“的元素?

+1

而你试过的代码? – yizzlez

+0

我还没有尝试过任何东西,我不知道如何。 – user3209342

+0

搜索“从文件列读取C++”的StackOverflow。 –

回答

0

使用一个fstreamifstream对象和提取操作符。

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

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

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相同。 同样,如果这真的是你需要的,你可以通过返回相应的向量来“返回一列”。

相关问题