Here is my assignment:
Create a program that would read the content of an input file and write it back to an output file with all the letters "C" changed into "C++". For example the following file:
"C is one of the world's most modern programming languages. There is no language as versatile as C, and C is fun to use."
should be changed and saved into another file with the following content:
"C++ is one of the world's most modern programming languages. There is no language as versatile as C++, and C++ is fun to use."
To read one character from the file you should use the get() function:
ifstream inputFile;
char next;
...
inputFile.get(next);
Inside the while loop, you should read one character, check to see if needs to be changed, and write it back (changed or unchanged) to the output file. To write one character you can use the stream operator "<<".
I created a helloFile.txt that looks like 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 32 33 34 35
|
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
ofstream myFile;
myFile.open("HelloFile.txt", ios_base::out);
if (myFile.is_open())
{
cout << "C is one of the world's most modern programming languages. There is no language as versatile as C, and C is fun to use." << endl;
string fileContents;
char ch;
while (myFile.good())
{
myFile.get(ch);
//check the character to see if it matches the specified condition
if ( ch == 'C' )
//write to the output file C++
myFile << "C++";
else
//write to the output file the unchanged character
myFile << ch;
}
if (myFile.is_open())
{
myFile << "C is one of the world's most modern programming languages. There is no language as versatile as C, and C is fun to use." << endl;
myFile.close();
}
return 0;
system ("Pause");
}
|
My other file looks like 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 32
|
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{
ifstream myFile;
myFile.open("HelloFile.txt", ios_base::in);
if (myFile.is_open())
{
cout << "C is one of the world's most modern programming languages. There is no language as versatile as C, and C is fun to use." << endl;
string fileContents;
char ch;
while (myFile.good())
{
myFile.get(ch);
//check the character to see if it matches the specified condition
if ( ch == 'C' )
//write to the output file C++
myFile << "C++";
else
//write to the output file the unchanged character
myFile << ch;
}
// close both streams
return 0;
}
|
It is not working. I need some guidance, please help