handling with files

hey guys how i read from files only int/or some char data
let say i have list of student name + grade in file
like
name1 80
name2 90
and i want to take from the file only the grades and not the name
i know how to handle files in c++ but still.

another quastion if i have the same name student + grades
and in the files its written like this:
name1|90
name2|30
how can i skip the name and the sign |.
i know how to handle seekg .
but the name have diffrent size .
any help i be really greatfull

Case 1: reading name and grade separated by space
1
2
3
4
5
6
7
8
ifstream src(filename);
string name;
int grade;
while (src >> name >> grade)
{
   // forget name;
   // use grade;
}


Case 2: reading name and grade separated by '|'
1
2
3
4
5
6
7
8
ifstream src(filename);
string name;
int grade;
while (getline(src, name, '|') >> grade)
{
   // forget name;
   // use grade;
}
how can i skip the name and the sign |

use the '|' character as a 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
# include <iostream>
# include <fstream>
# include <sstream>
# include <string>

int main()
{
    std::ifstream inFile{"C:\\test.txt"};
    if(inFile)
    {
        std::string first, second;
        while (getline(inFile, first, '|') && getline(inFile, second))
        {
            std::istringstream stream{second};
            double grade{};
            if(stream) stream >> grade;
            if(inFile)
            {
                    std::cout << grade << "\n";
            }
        }
    }
}
/* SAMPLE FILE
name1|90
name2|30
*/


thanks guys its worked
but i dont understand how sorry iam a bit new to files.
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
#include<iostream>
using namespace std;
#include<fstream>
#include<string>
#include<sstream>
void func(ifstream &);
int main() {
	ifstream file;
	file.open("data.txt", ios::in);
	if (!file) {
		throw "error";
	}
	func(file);

	system("pause");
	return 0;
}
void func(ifstream &file){
	
	string name;
	int grade;
	while (getline(file, name, '|') >> grade)
	{
		cout << name;

	}
	file.close();
	
}


while (getline(file, name, '|') >> grade) what this line is doing.?
Last edited on
Maybe a bit clearer if you break it into two pieces.
1
2
3
4
5
6
7
while (getline(file, name, '|'))  //Reads text until '|' or the end of line into name while file is valid
  {
    cout << name;
    file >> grade; // reads an int into grade
    cout << "\t" << grade; 

  }
thanks alot thomas .
Topic archived. No new replies allowed.