Code:
// Function for opening/writing to a file.
void WriteToFile ( char *file_name, char *text )
{
// Open file with ios::app to append
ofstream the_file ( file_name, ios::app );
// Check for file
if ( !the_file.is_open () ) {
cout << "Failed to open " << file_name;
exit ( 1 );
}
// Output the text and a newline
the_file << text << endl;
the_file.close ();
}
The ios::app goes to the end of the file to write so it doesnt overwrite whats already in the file.
Also the only thing my code example will do is write "Hello" to the file if you type "hello" and quite if you type "quit".
Just add more conditions to it and you will get more stuff.
Code:
do {
getline ( cin, the_string );
if ( the_string == "hello" ) WriteToFile ( "C:/CPU.txt", "Hello" );
else if ( the_string == "something" ) WriteToFile ( "C:/CPU.txt", "Why something?" );
} while ( the_string != "quit" );
Now using this method it is case sensitive. So "Hello" is different than "hello".
I would suggest you just play around with it until you understand what is going on with it. When you go "Ah ha!" then you will be ready for more
EDIT:
This code will be more efficent because you wont be opening and closing the file everytime you write to it.
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string the_string;
ofstream the_file ( "c:/CPU.txt", ios::app );
cout << "Talk to me." << endl;
do {
getline ( cin, the_string );
if ( the_string == "hello" ) the_file << "hi" << endl;
else if ( the_string == "quit" ) the_file << "bye" << endl;
else the_file << "I dont understand" << endl;
} while ( the_string != "quit" );
the_file.close ();
return 0;
}
Run that code and type
hello
llamma
quit
Then go to C:\ and you will see CPU.txt, open it and look.
OMG
I just realised what you want to do. I am so sorry. doh im so slow.
You want the information to be in a text file!!!!
So you want it to search the text file for certain keywords found in the user input string and write the apropriate reponses.
Jeez im so sorry, I am on some cold medication and the room is spinning so forgive my stupidity.
Ok well my code still aplies in theory but Im not familiar with searching files for text. Let me go look up some stuff.