So I'm working on my C++ final and I'm having a problem replacing a line in a text file. The code is supposed to look through the list and replace the work "open" with a name input by the user. This is basically what I have so far:
Now I'm pretty sure this should put the name entered by the user on the line after "open" in the text file, but it doesn't. So if someone could help me get that fixed and tell me how to remove a line from the file (so i can't remove the line that has "open"), that'd be great.
woops, sorry, that was just a typo in rewriting the code in the text box. There aren't any errors when I compile the program, so it's nothing like that.
#include <iostream>
#include <fstream>
#include <string>
int main()
{
std::string name; // String to store your name.
std::fstream flightOne; // fstream to hold the file.
flightOne.open("flightOne.txt");
std::cout << "Enter your name\n\n >> ";
std::cin >> name;
std::cout << std::endl;
std::string fileContent; // String to hold the files contents.
if(flightOne != NULL) // If the file is not NULL get it's contents.
{
std::string line; // String to temp store each line in the file.
while(std::getline(flightOne, line)) // Get each line inside the file.
{
fileContent += line; // Add the line to the fileContents string.
fileContent += "\n"; // Add a line break after each line you get.
}
flightOne.close(); // Need to close the file and open it again for writing.
std::cout << "--- Seats ---" << std::endl;
std::cout << fileContent; // Display the flight seats
std::cout << "-------------" << std::endl;
}
else
{
std::cout << "File is NULL" << std::endl; // Error: File is NULL
}
int position = fileContent.find("open"); // Find an 'open' position in the string.
if( position != -1 ) // If we have a valid position insert a new name into the string.
{
std::cout << "Found an open seat at position: " << position << " in the 'string'\n" << std::endl;
fileContent.erase(position, 4); // erase 4 positions from where open was found
fileContent.insert(position, name); // Insert 'name' to the position open was found.
flightOne.open("flightOne.txt"); // Open up the text file again.
flightOne.clear(); // Clear the current data in it.
flightOne << fileContent; // Write our updated string to the file.
flightOne.close(); // Close the file.
std::cout << "--- Seats ---" << std::endl;
std::cout << fileContent; // Display the edited string.
std::cout << "-------------" << std::endl;
std::cout << "Inserted " << name << " to the open seat" << std::endl;
}
else
{
std::cout << "*** Sorry - No seats avaliable ***" << std::endl;
}
return 0;
}