#include #include #include using namespace std; void main() { //Open "input.txt" for reading. fstream fin("input.txt"); //Open "output.txt" for writing - the ios::out parameter is required. This will overwrite if applicable. fstream fout("output.txt", ios::out); //Make sure "input.txt" and "output.txt" were opened properly. if (fin && fout) { //Tell them we're adding commas. cout << "Adding commas...\n\n"; //This will hold each line of characters that we read and write. string nextLine = ""; //This is an infinite loop - it will only break (exit) from the loop when we've reached the end of the file. while (true) { //Read the next line from the file. getline(fin, nextLine); //Check to see if we've reached the end of the file. If so, break out of the reading/writing while loop. if (!fin) { break; } if (nextLine.length() > 2) { nextLine.insert(3, ","); } //Output the next line. fout << nextLine << '\n'; } //Assume success since there were no file opening errors. cout << "Adding commas successful! Check \"output.txt\"."; } else { //The files were not opened properly - let the user know that it was unsuccessful. cout << "Error either opening \"input.txt\" for reading or opening \"output.txt\" for writing."; } //Close the files. fout.close(); fin.close(); //Output some new line characters before the program asks for a key press. cout << "\n\n"; system("pause"); }