I have a text file that looks like this (but many more lines):
9527,88147
4963,75407
448P,34361
2545,29046
9095,258T8
P
chars
T
#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
for removing chars, you can use erase()
and isalpha
for this matter. See the following
#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;
}
The txt file is
1,1
2,2
3,3
4P,4
5,5T
and the output is
average column 1: 3.0000 and max column 2: 5