Answer to Question #177716 in C++ for Talha

Question #177716

Create a file given“Address”with proper ios flags.

.

Write 5 lines in the file and each line should have a Student’s data in the following format:(10)


Name: Address: Phone Number

.


e.g


Alyan: Khayaban-e-Jinnah,UCP: 030012345678


Read the file and display all the numbers

Students

data whose number starts with 0300. (15)



1
Expert's answer
2021-04-03T16:52:46-0400
#include <iostream>
#include <string>
#include <fstream>
using namespace std;


int main()
{
	string path = "Address";
	fstream fs;
	fs.open(path, ios::out);
	if (!fs.is_open())
	{
		cout << "File creation error" << endl;
		exit(1);
	}
	else
	{
		cout << "File created and opened for writing" << endl;
		fs << "Alyan: Khayaban-e-Jinnah,UCP: 030012345678" <<"\n";
		fs << "Sandhu: Hafiz Hayat Campus: 0300987589" << "\n";
		fs << "Hamza: 1-KM Raiwind RoadLahore: 0300798123" << "\n";
		fs << "Arshad: Kazi Campus, Jamshoro-76080, Sindh: 0500987589" << "\n";
		fs << "Hou: Syed Abdul Qadir Jillani: 0600987589" << "\n";
		fs.close();
	}
	fs.open(path, ios::in);
	if (!fs.is_open())
	{
		cout << "File open  error" << endl;
		exit(1);
	}
	else
	{
		cout << "Opening a file and displaying numbers starting with 0300" << endl;
		while (fs)
		{
			string s;
			getline(fs, s);
			int index = s.find_last_of(' ');
			// last word in strig is telefone number
			string last_word = s.substr(++index);
			if (last_word.rfind("0300", 0) == 0)
			{
				cout << last_word << endl;
			}
		}
		
		fs.close();
	}
	return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS