The following code simply asks the user for their name and then prints "Hello, [name]!"
When run from a Windows command prompt it runs as expected with this output ("Jim" is input by the user):
What is your name? _ Jim
Hello, Jim!
I'd like to redirect the output (and the name inputted by the user) to a file. Essentially, I'd like to send exactly what is seen above to a text file and also see the program run in the command prompt. When I use this:
hello.exe > output.txt
the program doesn't display the question, "What is your name?" in the command prompt, but it is sent to the output.txt file. Then when a name is entered, the message "Hello, Jim!" is not displayed in the prompt, but it is sent to the text file. This is the contents of the text file:
What is your name? Hello, Jim!
It works as expected, but is there a way to see the program execute, then send exactly what is displayed in the command prompt to a text file?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
// request user's name and store in a variable
string name;
cout << "What is your name? ";
cin >> name;
// print "Hello" and the user's name
cout << "Hello, ";
cout << name << "!" << endl;
return 0;
}
#include <fstream>
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
// request user's name and store in a variable
string name;
cout << "What is your name? ";
cin >> name;cin.getline( cin , name );
// print "Hello" and the user's name
cout << "Hello, ";
cout << name << "!" << endl;
ofstream out( "filename.txt" ); //if the file doesn't exist it creates one
//after the filename you can put flags for other things like appending
//instead of writing over previous file
out << "Hello, " << name << "!" << endl;
//The file should close automatically but to be safe
out.close();
return 0;
}
#include <fstream>
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
// request user's name and store in a variable
string name;
cout << "What is your name? ";
getline( cin , name );
// print "Hello" and the user's name
cout << "Hello, ";
cout << name << "!" << endl;
ofstream out( "filename.txt" ); //if the file doesn't exist it creates one
//after the filename you can put flags for other things like appending
//instead of writing over previous file
out << "Hello, " << name << "!" << endl;
//The file should close automatically but to be safe
out.close();
return 0;
}
Yeah, both is what I was shooting for. But, I was trying to get the command prompt to do the output to the text file. Basically I just want to send what was displayed in the command prompt to the text file; but I guess there is not really a way to do this.
You can copy the entire program to a text file as long as every cout call is also sent to a file and every cin call is also copied across. You're then basically make a log file of everything that happened.