从文件的一行中查找数字的平均值,避免使用第一个单词
Finding average of numbers from one line of a file avoiding the first word
我有一个具有以下格式的文本文件:
U123 78 90 65 85
U234 87 98 90 56
U345 89 90 98 87
U456 45 56 67 78
第一个值 (Uxxx( 是"学生编号",同一行上的所有其他值都是考试成绩(第一个是考试 1,第二个考试 2,依此类推(
我正在尝试获取特定学生(由用户指定(的所有考试的平均值,但在如何存储特定行的考试值方面遇到问题。
我有一个不同的功能,可以显示指定学生的分数,并正在尝试对其进行修改以使其也为此工作,但遇到了麻烦。以下是该函数的代码:
void DisplayStudentScores()
{
string stuNum;
ifstream inFile;
inFile.open(scores.txt);
//for testing purposes
if(!inFile) {
cout << "File not found" << endl;
exit(1);
}
//end of test
cout << "Enter the Student ID of who's scores you would like to see: ";
cin >> stuNum;
cout << endl;
string line;
while(getline(inFile, line)){
if(line.find(stuNum) != string::npos){
cout << line << endl;
break;
}
else{
cout << "Student not found" << endl;
break;
}
}
}
字段用
空格整齐地分隔,因此流运算符比getline
更好:
string stu;
int score1, score2, score3, score4;
infile >> stu >> score1 >> score2 >> score3 >> score4;
你可以把它放在一个循环中:
while(infile >> stu >> score1 >> score2 >> score3 >> score4){
if(stu == stuNum){
// calculate and print average
return;
}
}
cout << "Student " << stuNum << " not found" << endl;
相关文章:
- 文本文件中的单词链表
- 计算数组c++的平均值
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 计算平均值,不包括上次得分
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 彩色图像的卤化物处理平均值
- 如何创建一个函数来计算并返回平均值、最大值和最小值
- 使用if-else将数字转换为单词
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 按平均值替换数组中的元素
- 如何返回多个矢量对象的平均值?C++
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 从文件的一行中查找数字的平均值,避免使用第一个单词