Questions and codes:
/* *copyright (c) 2015, *all Rights reserved, School of computer and Control engineering, Yantai University. * File name: Test.cpp * Author: wenqing * Completion Date: June 18, 2015 * Version number: v1.0 * * Problem Description: Read in a C + + program so that all the left curly braces "{" and the closing curly brace "}" in the program take a separate line, the new program is saved to another. cpp file, and Displays the processed program on the screen, plus the line number when displayed. * Program Input: * Program output: */
#include <fstream> #include <iostream> #include <cstdlib>using namespace Std;int main () {// Reads the data in the file into a character array ifstream sourcefile ("Source.cpp", ios::in); Open file as input if (!sourcefile)//test successfully opened {cerr<< "source code read error!" <<endl; Exit (1); } ofstream outFile ("Newsource.cpp", ios::out); Open File as Output if (!outfile)//test successfully opened {cerr<< "new source code write error!" <<endl; Exit (1); } char Ch1,ch2; Represents a front and back two characters while (!sourcefile.eof ()) {sourcefile.get (CH2); No wrapping before curly braces, add line break if (ch2== ' {' | | | ch2== '} ') && (ch1!= ' \ n ')) outfile.put (' \ n '); No wrapping after curly braces, add newline character else if ((ch1== ' {' | | | ch1== '} ') && (ch2!= ' \ n ')) outfile.put (' \ n '); Outfile.put (CH2); The output is currently read in the symbol CH1=CH2;//CH1 assigned to CH2 characters, CH2 continue to read down} outfile.close (); Sourcefile.close (); Add line number after output cout<< "after processing the source program is:" <<endl; Char line[256];int n=1; Ifstream inFile ("Newsource.cpp", ios::in); Open file as input if (!infile)//test successfully opened {cerr<< "File open error!" <<endl; Exit (1); } while (!infile.eof ()) {Infile.getline (line,255, ' \ n '); cout<<n<< ". \ t" <<line<<endl; n++; } infile.close (); return 0;}
Operation Result:
Summary of Knowledge points:
Line breaks and line numbers can be difficult to arrange, so separating the two steps will make programming easier.
Before and after identifying curly braces, set two character types
14th Week Item 4-2:ide curly braces wrapping mechanism