Need advice with I/O Streams and Data Files

Well we're on I/O streams dealing with reading and writing to a data file in my C++ class and im completely lost. I just got over having swine flu and I'm pretty far behind. My book doesn't give any great examples on writing to a data file so I figured I'd ask here.

The assignment is:

<i>Write a C++ program that accepts lines of text from the keyboard and writes each line to a file name text.dat until an empty line is entered. An empty line is a line with no text that is created by pressing the Enter (or Return) key.</i>

and heres my code so far:


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
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{
	string filename = "text.dat";
	string line;
	ifstream inFile;
	
	inFile.open(filename.c_str());
	
	if (inFile.fail())
	{
		cout << "\nThe file was not found or is non-existant.  \nPlease check to see if the file exists." << endl;
		exit(1);
	}
	if (inFile.is_open())
	{
	if (line != "")
	{
		cout << "Enter a a line of text:" << endl;
		cin >> line;	
	}
	}
	inFile.close();
	return 0;
}


But when I run it, it doesn't actually do anything is just exits right away. Any help would be appreciated. Thank you =)
Replace the if of lines 22-26 with a do-while and line 25 with getline(cin,line);
Thanks so much, the input is working. But now it isn't writing it to the file. I should be able to figure this out though.
Last edited on
Hint: You need a file for output, not for input
Ok, i changed it to this:

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
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{
	string filename = "text.dat";
	string line;
	ofstream outFile;
	
	outFile.open(filename.c_str());
	
	if (outFile.fail())
	{
		cout << "\nThe file was not found or is non-existant.  \nPlease check to see if the file exists." << endl;
		exit(1);
	}
	if (outFile.is_open())
	{
	do
	{
		cout << "Enter a a line of text:" << endl;
		getline(cin,line);
	}
	while (line != "");
	}
	outFile.close();
	return 0;
}


but it still isn't writing to file.
Last edited on
Where are you expecting it to write?
Read carefully your code and you'll realise that you never tell to write anything on that file
Yes, what you have done here is

1.) You open the file.
2.) You ask for the word.
3.) And you get that line.

In here, there is no code that you says that you put it in your textfile.

Read on I/O handling.

Regards,
Nemesis
Topic archived. No new replies allowed.