Another I/O File Problem

Trying to write to a file a person's name first and last then there telephone number. I want the program to loop until the user enters "quit" for the name.
I want to store the name as in the format First Last. And the phone number as example: (734)555 1212. Displaying contents when user enters quit.

Here is what I have so far. I know I need to use a loop for entering the data and loop until the user enters quit.
Stuck on what to do for formatting and what to use for the loop.

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
//Writing data to a file.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>


using namespace std;

int main()
{
	ofstream outputFile;
    string nameFirst, nameLast;
	int phoneNumber;
	

	outputFile.open("phonebook.txt");

	cout << "Enter your first name: " << endl;
	cin >> nameFirst;
	cout << "Enter your last name: " << endl;
	cin >> nameLast;
	cout << "Enter your phone number: " << endl;
	cin >> phoneNumber;
	cout << "The numbers were saved to a file. \n";

	

	

	//Close the file.
	outputFile.close();
	cout << "Done. \n";
	system ("pause");
	return 0;
}
Last edited on
Consider using a string for the phone number, as you are using 7-10 digits and this will show up as a exponent. And since you won't be doing any mathematical functions with them.

As for the text file,
1
2
3
cout << "Enter your first name: " << endl;
cin >> nameFirst;
outputFile<<nameFirst<<endl;
should work.
Yes that worked and made more sense. I want the user inputs to loop until the user enters the word quit. I tried using a while loop to do this and think that my test expression is faulty. I also want to format the telephone number in a (313) 545-5544 format and are unsure how to do this.
Here is my changed 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
46
47
48
49
//Writing data to a file.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>


using namespace std;

int main()
{
	ofstream outputFile;
	string firstName, lastName, phoneNumber, quit;





	outputFile.open("phonebook.txt");




	while ( firstName != quit );
	{

		cout << "Enter your first name: " << endl;
		cin >> firstName;
		cout << "Enter your last name: " << endl;
		cin >> lastName;
		cout << "Enter the telephone number: " << endl;
		cin >> phoneNumber;
		cout << "The numbers were saved to a file. \n";


		//Write the names and phone number to a file.
		outputFile << firstName << " " << lastName << " " << phoneNumber << endl;

	}




	//Close the file.
	outputFile.close();
	cout << "Done. \n";
	system ("pause");
	return 0;
}
Topic archived. No new replies allowed.