我在编写一个程序的一部分时遇到了麻烦,该程序将读取一个名称和一个文件中的10个数字.fie称为grades.dat数据文件的结构是:
Number One
99 99 99 99 99 99 99 99 99 99
John Doe
90 99 98 89 87 90.2 87 99 89.3 91
Clark Bar
67 77 65 65.5 66 72 78 62 61 66
Scooby Doo
78 80 77 78 73 74 75 75 76.2 69
Run Code Online (Sandbox Code Playgroud)
这就是我获取数据的功能,我甚至不确定这是否正确.
void input (float& test1, float& test2, float& test3, float& test4, float& test5, float& test6, float& test7, float& test8, float& test9, float& test10, string& studentname)
{
ifstream infile;
infile.open ("grades.dat");
if (infile.fail())
{
cout << "Could not open file, please make sure it is named correctly (grades.dat)" << "\n" << "and that it is in the correct spot. (The same directory as this program." << "\n";
exit(0);
}
getline (infile, studentname);
return;
}
Run Code Online (Sandbox Code Playgroud)
Ker*_* SB 10
使用标准C++习语,一次读取两行(如果不可能则失败):
#include <fstream>
#include <sstream>
#include <string>
#include <iterator> // only for note #1
#include <vector> // -- || --
int main()
{
std::ifstream infile("thefile.txt");
std::string name, grade_line;
while (std::getline(infile, name) && std::getline(infile, grade_line))
{
std::istringstream iss(grade_line);
// See #1; otherwise:
double d;
while (iss >> d)
{
// process grade
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果内部循环(标记#1)的唯一目的是存储所有等级,那么@Rob建议您可以使用流迭代器:
std::vector<double> grades (std::istream_iterator<double>(iss),
std::istream_iterator<double>());
Run Code Online (Sandbox Code Playgroud)
流迭代器与while上面的内部循环做同样的事情,即它迭代类型的标记double.您可能希望将整个矢量插入到容纳std::pair<std::string, std::vector<double>>名称和等级对的大容器中.