Reading numbers in from file

Hey in my C++ code, here is my input file
1
2
3
4
5
6
7
8
30713 4 3 3 4 3 3 2 3 4 3  
21356 4 4 4 3 3 3 2 3 2 3  
21265 4 1.5 3 3 3 0.5 2 3 3 3  
19364 4 3 3 3 -1   
19335 0 3 0 4 2 3 3 1.5 -1    
18264 2 3 3 0.5 3 0.5 3 3 2 3  
20135 4 1 3 4 3 1.5 0 3 -1  
22185 4 3 4 4 4 3 3 3 4 3 


The first number in each line represents the ID number, and the rest of numbers are varying (grade and credit hour)

How would I read the ID number in by itself and then read the grade and credit hour one set a time?
My teacher recommended that we have another loop in the while loop to read the grade and credit hours.

something like this
1
2
3
4
while (!infile.eof())
{
OutputFile<<ID<<setw(15)<<"Coming Soon"<<endl;
}
Last edited on
"while (!infile.eof())" is an error, but the idea is sound: have a loop that reads the file line by line, and another loop inside that reads the individual numbers from the line. For example,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;
int main()
{
    std::ifstream f("test.txt");
    std::string line;
    while(getline(f, line))
    {
        std::istringstream linebuf(line);
        int id;
        linebuf >> id;
        std::cout << "ID = " << id;
        double grade, hours;
        while(linebuf >> grade >> hours)
        {
             std::cout << " g = " << grade << " h = " << hours;
        }
        std::cout << '\n';
    }
}
This is what a stringstream is for. Also, don't loop on EOF.

1
2
3
4
#include <iostream>
#include <sstream>
#include <string>
#include <vector> 
1
2
3
4
5
struct student_credits_t
{
  unsigned     ID;
  vector <int> credit_hours;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
vector <student_credits_t> all_student_credits;

student_credits_t credits;
while (infile >> credits.ID)
{
  string s;
  getline( infile, s );

  credits.credit_hours.clear();
  int credit;
  istringstream ss( s );
  while (ss >> credit)
  {
    credits.credit_hours.push_back( credit );
  }

  all_student_credits.push_back( credits );
}

It might be worth your time to put some of that stuff in a function.

Hope this helps.
Topic archived. No new replies allowed.