Reading from file

closed account (3pX8b7Xj)
My Code Work fine but i am having a problem i want to store full name in one string not to create each string for one name

My code take student id from user and display their content

source code

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
38
39
40
41
42
43
44
45
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

int main(){

	string name1, name2,program;
	int id, choise;

	ifstream data;
	data.open("data.txt");

	while (true)
	{
		cout << "\nEnter The Student ID : ";
		cin >> choise;
		while (data >> id >> name1 >> name2 >> program)
		{
			if (id == choise)
			{
				cout << "\nStudent Name : " << name1 
				<< " " << name2 << endl;
				cout << "\nStudent ID : " << id << endl;
				cout<<"\nProgram : "<<program;
				cout<<endl;
			}
		}

		data.clear();
		data.seekg(0, ios::beg);

		cout << "\n1 To Try Again : ";
		cin >> choise;
		if (choise == 1)
		{
			system("cls");
			continue;
		}
		else
			break;
	}
	system("pause");
}


text file data
24123
Muhammad Salman
BS(CS)
24124
Muhammad Baqir
BS(SE)
24125
Hamza Rizwan
BBA
Last edited on
Simplest way you can imagine :
1
2
3
4
string fullName;
while (data >> id >> name1 >> name2 >> program)
{
    fullName = name1 + ' ' + name2;
closed account (3pX8b7Xj)
I want to do this

thanks for your replay


1
2
3
4
5
6
while(data>>id>>name>>program)
{
         cout<<"\nName : "<< name << endl;
         cout<<"\nId : "<< id << endl;
         cout<<"\nProgram : "<< program << endl;
}


output that i want to show

Name : Muhammad Salman
Id : 24058
Program : BS(CS)

but i will get this

Name : Muhammad
Id : 24058
Program: Salman

plz help





Choose a longer one.
1
2
3
4
5
6
while(data >> id && (data.ignore(20, '\n'), getline(data, name)) && data >> program)
{
         cout<<"\nName : "<< name << endl;
         cout<<"\nId : "<< id << endl;
         cout<<"\nProgram : "<< program << endl;
}
Last edited on
closed account (3pX8b7Xj)
thanks hanaka

can you please tell me why do you use (data.ignore(20, '\n'), getline(data, name))

i am doing c++ for 4 months

can you plz tell me how to improve logic and good book to read

now program is working fine

thnx
Last edited on
http://www.cplusplus.com/reference/istream/istream/ignore/
http://www.cplusplus.com/reference/string/string/getline/
closed account (3pX8b7Xj)
thnx
Topic archived. No new replies allowed.