Counting data input file
Apr 9, 2021 at 3:24pm UTC
I am working on a program that has an input file containing a students last name, first name, and grade. What I need the program to do is count how many people are in each grade then display is.
For example...
Smith#Bob#11
Doe#John#11
Fork#Spoon#10
Musk#Elon#9
It should display
“There are 2 students in 11th grade”
“There is 1 student in 10th grade”
“There is 1 students in 9th grade”
I am stuck on the part that actually counts how many students are in each grade, any help would be appreciated:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <fstream>
#include <iostream>
#include <string>
using std::ifstream;
using std::ios;
using namespace std;
int main(void ) {
ifstream cstudent;
string name;
string name1;
int grade = 0;
int fre = 0;
int sop = 0;
int jun = 0;
cstudent.open("Period7.txt" );
if (cstudents.is_open()) {
getline(cstudents, name1, ',' );
getline(cstudents, name, ',' );
cstudents >> grade;
if (grade == 9)
fre++;
if (grade == 10)
sop++;
if (grade == 11)
jun++;
cout << "There is " << fre << " student in 9th grade" << endl;
cout << "There are " << sop << " students in 10th grade" << endl;
cout << "There are " << jun << " students in 11th grade" << endl;
cstudents.close();
} else
cout << "Error in opening" ;
}
Apr 9, 2021 at 5:17pm UTC
Perhaps using # as delimiter:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::ifstream cstudents("Period7.txt" );
if (cstudents.is_open()) {
std::string name;
std::string name1;
int grade {};
int fre {};
int sop {};
int jun {};
while (std::getline(cstudents, name1, '#' ) && std::getline(cstudents, name, '#' ) && cstudents >> grade)
if (grade == 9)
++fre;
else
if (grade == 10)
++sop;
else
if (grade == 11)
++jun;
std::cout << "There are " << fre << " student(s) in 9th grade\n" ;
std::cout << "There are " << sop << " student(s) in 10th grade\n" ;
std::cout << "There are " << jun << " student(s) in 11th grade\n" ;
} else
std::cout << "Error in opening\n" ;
}
There are 1 student(s) in 9th grade
There are 1 student(s) in 10th grade
There are 2 student(s) in 11th grade
Apr 9, 2021 at 6:38pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
istringstream in( "Smith#Bob#11 \n"
"Doe#John#11 \n"
"Fork#Spoon#10 \n"
"Musk#Elon#9 \n" );
int main()
{
const int N = 13; // Or whatever; it's 13 in Britain
int grade[1+N] = { 0 };
// ifstream in( "Period7.txt" );
for ( string s; in >> s; )
{
int p = s.find_first_of( "0123456789" );
if ( p != string::npos ) grade[stoi(s.substr(p))]++;
}
for ( int i = 1; i <= N; i++ ) if ( grade[i] > 0 ) cout << "There are " << grade[i] << " student(s) in year " << i << '\n' ;
}
Topic archived. No new replies allowed.