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:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
usingnamespace 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:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <cmath>
usingnamespace 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;
}