Write a C++ program that opens a text file with the name "Hello.txt", creates a second file "Hello1.txt". Read the content of Hello.txt and copy its contents to Hello1.txt " replacing every space character ' ' with a '_' character. Thus the text "The quick brown " in Hello.txt should become "The_quick_brown_" Close both files. Remember to include string and fstream. You will have to use the get function of your ifstream object.
please please help. I know how to do this question:
Write C++ code to open a file with the name Hello.txt, store the message
“Hello, World!” in the file, and close the file. Then open the same file
again and read the message into a string variable. Close the file again.
ofstream output_data;
output_data.open("Hello.txt");
output_data %26lt;%26lt; "Hello, World!";
output_data.close();
ifstream input_data;
input_data.open("Hello.txt");
string s;
getline(input_data, s);
input_data.close();
But I cannot get this one!
C++ program?
The get() version
ifstream input_file("Hello.txt");
ofstream output_file("Hello1.txt");
ch = input_file.get();
while (!input_file.eof())
{
if (ch == ' ')
ch = '_';
output_file.put(ch);
ch = input_file.get();
}
input_file.close();
output_file.close();
Reply:Read the file in as an entire block:
// read a file into memory
#include %26lt;iostream%26gt;
#include %26lt;fstream%26gt;
using namespace std;
int main () {
int length;
char * buffer;
ifstream is;
is.open ("test.txt", ios::binary );
// get length of file:
is.seekg (0, ios::end);
length = is.tellg();
is.seekg (0, ios::beg);
// allocate memory:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
is.close();
cout.write (buffer,length);
delete[] buffer;
return 0;
}
Then iterate through each character in the buffer, replacing " " with an _
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment