Basic file input/output program

Hey everyone,

This is my first post, although I have some history of eye-balling this forum when I was stuck on something. I'm trying to write a pretty basic code (or so I think) that outputs the content of a file (test.txt in my case) onto the screen. The user is also then supposed to be able to input something into that file after the initial content gets printed onto the screen, but I'm just tackling the first part for now (i.e. getting the content of the file printed on the screen). I have this 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
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>

using namespace std;

int main()
{

	char control = 'y';//this variable is used by user to stay in or exit out of do-while loop

	do
	{
		ifstream in_stream;
		in_stream.open("test.txt");

		cout << "The previous piece of advice is given below:\n\n";
		char next;
		while (!in_stream.eof())
		{
			in_stream.get(next);
			cout << next;
		}
		in_stream.close();

		cout << "Would you like to run the program again? (Y/N): ";
		cin >> control;
		while ((control != 'y') && (control != 'n'))
		{
			cout << "Incorrect input. Would you like to run the program again? (Y/N): ";
			cin >> control;
			control = tolower(control);
		}
		
	}while(control == 'y');
	
	cout << "Press key to exit: ";
	char exit;
	cin >> exit;

	return 0;
}


It works fairly well as long as the content of the file ends in a newline ("\n") but when the file ends in any other kind of character, let's say "3" for example, then the last character gets repeated twice. So for example if test.txt contains:

"1
2
3"

Then the output that's printed is:

"1
2
33"

When I actually mean to have it print:

"1
2
3"

Any suggestions? Thanks.
I solved my own problem. Here's the 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 <fstream>
#include <cstdlib>
#include <cmath>

using namespace std;

int main()
{

	char control = 'y';//this variable is used by user to stay in or exit out of do-while loop

	do
	{
		ifstream in_stream;
		in_stream.open("test.txt");

		cout << "The previous piece of advice is given below:\n\n";
		char next;

		in_stream.get(next);
		while (!in_stream.eof())
		{
			cout << next;
			in_stream.get(next);
		}
		in_stream.close();

		cout << "Would you like to run the program again? (Y/N): ";
		cin >> control;
		while ((control != 'y') && (control != 'n'))
		{
			cout << "Incorrect input. Would you like to run the program again? (Y/N): ";
			cin >> control;
			control = tolower(control);
		}
		
	}while(control == 'y');
	
	cout << "Press key to exit: ";
	char exit;
	cin >> exit;

	return 0;
}
Topic archived. No new replies allowed.