Hello, I've been searching this website for hints on how to search and replace a string from a text file. What I've come up with is a program that opens and reads a text file and gets each line in a buffer. In each line, it is supposed to find and replace strings that I have initiated. However, I am not sure if it is finding and replacing anything. Below is my code, are there any modifications anyone can suggest? Thank you all.
// print the content of a text file.
#include <iostream>
#include <fstream>
usingnamespace std;
int main () {
// This is where we'll put the stuff we read from file
char buffer[ 100 ];
// Fill the buffer with zeros (char strings must be null-terminated)
fill_n( buffer, 100, '\0' );
ifstream infile;
infile.open ("myfile.txt", ifstream::in);
while (infile.good())
// Read as many as 100 bytes (chars) from the file and stick them in our array
infile.read( buffer, 100 );
// Convert that char array into a STL string, and show the user what we got.
string g( buffer );
string str2="exit";
string str="t";
g.replace(g.find(str2), str2.length(), "str");
cout << buffer << " successfully read from file.\n";
infile.close();
return 0;
}
I'm not sure, but this is what the build reported...
--------------------Configuration: work1 - Win32 Debug--------------------
Compiling...
catcode.cpp
C:\Documents and Settings\Administrator\Desktop\catcode.cpp(36) : error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >' (or t
here is no acceptable conversion)
Error executing cl.exe.
I have a new problem. I want to convert the elements in the string "g" into a character so that I can store them into a buffer and output those contents into a new file. How would I do this?
// print the content of a text file.
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
FILE * pFile;
pFile = fopen ( "myfile2.bin" , "wb" );
// This is where we'll put the stuff we read from file
char buffer[ 800 ];
// Fill the buffer with zeros (char strings must be null-terminated)
fill_n( buffer, 800, '\0' );
ifstream infile;
ofstream outfile;
outfile.open("myfile2.txt");
infile.open ("myfile.txt", ifstream::in);
while (infile.good())
{
// Read as many as 100 bytes (chars) from the file and stick them in our array
infile.read( buffer, 800 );
// Convert that char array into a STL string, and show the user what we got.
string g( buffer );
string str2="trail";
string str="no";
g.replace(g.find(str2), str2.length(), str);
cout << g << " successfully read from file.\n";
fwrite (buffer, 1 , sizeof(buffer) , pFile );
fclose (pFile);
infile.close();
}
return 0;
}