heres what i have already: #include <iostream> #include <fstream> #include <stri
ID: 3543274 • Letter: H
Question
heres what i have already:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void analyzeData(string fileName) ////function
{
ifstream infile(fileName);
int tmp = 0;
int count = 0;
int nums[9] = { 0 };
float percents[9]; /////hold 9 floats
if (!infile.good() )
return;
while(!infile.eof()) // if didnt reach end of file
{
infile >> tmp;
tmp = first(tmp);
if(tmp > 0)
{
nums[tmp - 1] ++;
count++;
}
}
for(int i = 0; i < 9; i++) //////
percents[i] = (float)nums[i]/count;
cout << fileName << " count: " << count << " ";
for(int i = 0; i < 9; i++) //////
cout << i + 1 << " : " << nums[i] << ", " << percents[i] << " ";
cout << " ";
return;
}
Explanation / Answer
#include <iostream>
#include <fstream>
#include <string>
#include<sstream>
using namespace std;
void analyzeData(string fileName) ////function
{
ifstream infile(fileName);
if (!infile.good())
{
cout << "Unable to open file " <<fileName << " so Exiting from program. " << endl;
return;
}
int tmp = 0;
int count = 0;
int nums[9] = { 0 };
float percents[9]; /////hold 9 floats
while(!infile.eof()) // if didnt reach end of file
{
infile >> tmp;
stringstream ss;
ss << tmp;
int first_digit = ss.str()[0]-'0';
if(first_digit > 0)
{
nums[first_digit - 1] ++;
count++;
}
}
for(int i = 0; i < 9; i++) //////
percents[i] = (float)nums[i]/count;
cout << fileName << " count: " << count << " ";
for(int i = 0; i < 9; i++) //////
cout << i + 1 << " : " << nums[i] << ", " << percents[i] << " ";
cout << " ";
return;
}
int main()
{
analyzeData("citypopulations.txt");
analyzeData("librarybooks.txt");
analyzeData("sunspots.txt");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.