Trying to Parse and Edit a Text File

I have this project for school where I basically need to write a program that will take any text file and convert it into html code.

1
2
3
4
5
6
7
8
9
string line;
	int lineCount = 0;

	while (!inFile.eof()) {
		getline(inFile, line);
		cout << line << endl;
		lineCount++;
	}
	cout << lineCount - 1 << " lines of text read in this file." << endl;


I have this block of code to print each line of the text file into the terminal window and count the number of lines printed. But I don't know how to make it change a single character or set of characters to something else. For example, if a line of text begins with the number "1", I want to be able to change it to "<h1>".

Any help is appreciated. Thanks.
1
2
3
4
5
6
7
8
while( std::getline( inFile, line ) ) { // the canonical loop to read each line of a text file
    
     if( !line.empty() && line[0] == '1' ) // if a line of text begins with the number "1"
            line = "<h1>" + line.substr(1) ; // change the "1" to "<h1>"

    // ...

}
Don't loop on EOF.

1
2
3
4
	while (getline(inFile, line))
	{
		...
	}

You have not said much about your text, except to suggest it looks something like a roff-style typesetting markup.

You can simply compare the beginning of the line for whatever string you are looking for:

1
2
		if (line.compare( 0, 2, "1 " ) == 0) 
			outFile << "<h1>" << line.substr( 2 ) << "</h1>\n";

Hope this helps.
Topic archived. No new replies allowed.