For my computer science class, we were told to try to read from a text document and have it replace every letter of C to C++
#include <iostream> // allows for cin and couts.
#include <fstream> // allows for the program to be able to read files.
using namespace std;
int main()
{
char str[1000000]; // used to store each letter.
int i = 0; // was supposed to be used as a counter to count the places of each letter within the array.
ifstream getExtraCredit(str); // opening file.
getExtraCredit.open("extracredit.txt");
char c;
if (!getExtraCredit) // If the read file isn't in the proper folder.
{
cout << "Error opening data file. " << endl;
}
else
{
while (getExtraCredit.get(c))
{
cout << c; // displays each character.
}
}
getExtraCredit.close(); // ends file reading.
system("PAUSE");
return 0;
}
inside the extracredit.txt file is
"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."
I am very confused on how to do this. Several post on the site says to use a "replace" function, but it seems that only works with strings and my instructor's specific instructions were to keep it as a char array.
From my understanding, would it not make more sense to use string instead of char? What I am confused on is how would I do this with using chars. If I was using strings, my assumption on how it would be done would be having the project read the file and store it within string arrays. From there, the array would be read and if it contains C's, it would be replaced by a C++ string.
His instructors are
Create a program proj5_3.cpp 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++". The names of input/output files are entirely up to you. For example the following file 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."
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);
first edit revision:
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string txt;
string temp;
ifstream getExtraCredit(txt); // opening file.
getExtraCredit.open("extracredit.txt");
if (!getExtraCredit)
{
cout << "Error opening data file. " << endl;
}
else
{
{
getline(getExtraCredit, temp); // displays each character.
txt.append(temp);
replace(txt.begin(), txt.end(), 'c', 'c++');
cout << txt;
}
}
getExtraCredit.close();
system("PAUSE");
return 0;
}
I am now having issues with using the replace function. Any insight on what I am doing wrong?