如何从文本文件中取出每一行并对它们进行平均?
How do I take each line from a text file and average them?
我在读取文本文件时遇到问题。取每一行数字,对数字进行平均,然后将这些数字推入一个向量。
70 79 72 78 71 73 68 74 75 70
78 89 96 91 94 95 92 88 95 92
83 81 93 85 84 79 78 90 88 79
这只是部分文件。都不知道怎么放了,肯定没必要。
我已成功打开文件。我在网上到处查看如何阅读每一行并尝试对数字进行平均。然而,我总是以失败告终。我是 C++ 的初学者,所以我很抱歉了解不多。
如何从文件中提取每一行并对它们进行平均以将其推送到向量?
int main() {
string inFileName = "lab1.txt";
ifstream inFile;
vector<string> scores;
string myLine2;
openFile(inFile, inFileName);
getAvgofContents(inFile, myLine2);
}
void openFile(ifstream &file, string name){
file.open(name);
while (!file.is_open()) {
cout << "Unable to open default file/file path.\nPlease enter a new file/file path:" << endl;
cin >> name;
file.open(name);
}
cout << "FILE IS OPEN!!!\n";
}
void getAvgofContents(ifstream &file, string line){
while (file){
getline(file, line);
cout << line << endl;
}
}
I am supposed to get results like:
73
81.5
84.1
...
...
Then after averaging each line, push the results to a vector.
这可能有帮助:
float getAvgOfLine(string line) {
float total = 0;
int count = 0;
stringstream stream(line);
while(1) {
int n;
stream >> n;
if(!stream)
break;
total += n;
count++;
}
if (count == 0) {
// the line has no number
return 0;
}
return total/count;
}
float getAvgofContents(ifstream &file, string line){
float total;
int number;
while (getline(file, line)){
cout << getAvgOfLine(line)<< endl;
}
}
参考:Convert String containing several numbers into integers
我在读取文本文件时遇到问题。取每一行数字,对数字进行平均,然后将这些数字推入一个向量。
70 79 72 78 71 73 68 74 75 70
78 89 96 91 94 95 92 88 95 92
83 81 93 85 84 79 78 90 88 79
这只是部分文件。都不知道怎么放了,肯定没必要。
我已成功打开文件。我在网上到处查看如何阅读每一行并尝试对数字进行平均。然而,我总是以失败告终。我是 C++ 的初学者,所以我很抱歉了解不多。
如何从文件中提取每一行并对它们进行平均以将其推送到向量?
int main() {
string inFileName = "lab1.txt";
ifstream inFile;
vector<string> scores;
string myLine2;
openFile(inFile, inFileName);
getAvgofContents(inFile, myLine2);
}
void openFile(ifstream &file, string name){
file.open(name);
while (!file.is_open()) {
cout << "Unable to open default file/file path.\nPlease enter a new file/file path:" << endl;
cin >> name;
file.open(name);
}
cout << "FILE IS OPEN!!!\n";
}
void getAvgofContents(ifstream &file, string line){
while (file){
getline(file, line);
cout << line << endl;
}
}
I am supposed to get results like:
73
81.5
84.1
...
...
Then after averaging each line, push the results to a vector.
这可能有帮助:
float getAvgOfLine(string line) {
float total = 0;
int count = 0;
stringstream stream(line);
while(1) {
int n;
stream >> n;
if(!stream)
break;
total += n;
count++;
}
if (count == 0) {
// the line has no number
return 0;
}
return total/count;
}
float getAvgofContents(ifstream &file, string line){
float total;
int number;
while (getline(file, line)){
cout << getAvgOfLine(line)<< endl;
}
}
参考:Convert String containing several numbers into integers