我有一个看起来像这样的文本文件(但还有更多行):
9527,88147
4963,75407
448P,34361
2545,29046
9095,258T8
如何找到第一列中所有数字的平均值?我知道如何找到平均值,但由于第1列中的一个数字中的P
,我似乎无法使其工作。所以我如何在忽略chars
的情况下找到平均值?
另外,如何在忽略char T
的同时在第2列中找到最大数字?
以下是我计算平均值的代码:
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
int main()
{
ifstream file;
string fileName;
cout << "Please input the filename: ";
cin >> fileName;
file.open(fileName.c_str());
while(file.fail())
{
file.clear();
cout << "Incorrect filename, please input the filename: ";
cin >> fileName;
file.open(fileName.c_str());
}
// Calculate the average value of all numbers in the first column and the
// largest value of all numbers in the second column
string line;
long sum = 0;
long i = 0;
long max = 0;
while (getline(file,line))
{
string str1, str2;
size_t idx = line.find(",");
str1 = line.substr(0,idx);
str2 = line.substr(idx+1);
str1.erase(std::remove_if(str1.begin (), str1.end (), ::isalpha), str1.end ());
str2.erase(std::remove_if(str2.begin (), str2.end (), ::isalpha), str2.end ());
int n;
sum += stoi(str1);
n = stoi(str2);
if(i == 0)
max = n;
else
{
if ( n > max )
max = n;
}
++i;
}
// The total number of rows in the file
int rows = 0;
{
++rows;
}
// Find the invalid numbers with letters in them and output them
file.close();
// Output of calculations
cout.precision(4);
cout << "The average value of all numbers in the first column: " << fixed << static_cast<double>(sum)/i << endl;
cout << "The largest value of all numbers in the second column: " << max << endl;
cout << "The total number of rows in the file is: " << i << endl;
//cout << "The invalid numbers are: " << letters << endl;
return 0;
}
我的平均值输出只是nan
。
答案 0 :(得分:1)
要删除字符,您可以使用erase()
和isalpha
来解决此问题。请参阅以下
#include <iostream>
#include <algorithm>
#include <fstream>
#include <string>
#include <iomanip> // std::setprecision
using namespace std;
int main()
{
ifstream file("data.txt");
string line;
long sum = 0;
long i = 0;
long max = 0;
while ( getline(file, line) ) {
string str1, str2;
size_t idx = line.find(",");
str1 = line.substr(0,idx);
str2 = line.substr(idx+1);
str1.erase(std::remove_if(str1.begin (), str1.end (), isalpha), str1.end ());
str2.erase(std::remove_if(str2.begin (), str2.end (), isalpha), str2.end ());
int n;
sum += stoi(str1);
n = stoi(str2);
if( i == 0 )
max = n;
else{
if ( n > max )
max = n;
}
++i;
}
cout.precision(4);
cout << "average column 1: " << fixed << static_cast<double>(sum)/i << " and max column 2: " << max << endl;
}
txt文件是
1,1
2,2
3,3
4P,4
5,5T
,输出
average column 1: 3.0000 and max column 2: 5