How to edit the specific line in a text file? - c++

How should I edit the specific line in a text file? And how should I avoid overwriting issue. ( How do I keep the record I had added before instead of replacing them by the new records?)
I tried to use line.replace but it says " No matching member function for call to replace ".
else if(choice == 4){
// count++;
string edit;
string newdate;
double newincome;
double newoutcome;
double EditTodayBalance = 0;
string emptySpace = " ";
// string sentence;
cout << " There are " << count << " record(s) in the file " << endl;
cout << " Please enter the date to edit " << endl;
cin >> edit;
size_t pos;
ifstream Record("BankRecord.txt");
if (Record.is_open()) {
while (getline(Record, line)) {
pos = line.find(edit);
if (pos != string::npos) // string::npos is returned if
string is not found
{
cout << line << endl;
cout << " Enter what you want to replace " << endl;
cout << " Please enter the new date you want to put " << endl;
cin >> newdate;
cout << " Please enter the new income you want to put " << endl;
cin >> newincome;
cout << " Please enter the new outcome you want to put " << endl;
cin >> newoutcome;
cout << " Your new Record is " << endl;
cout << count << emptySpace << newdate << emptySpace << newincome << emptySpace << newoutcome << endl;
//line.replace()
}
}
}
EditTodayBalance = newincome - newoutcome;
cout << " Today's balance is " << EditTodayBalance << endl;
cout << " Please reenter your choice " << endl;
cin >> choice;
}
I expect if the old line is " 1 2/2/2019 32 21 " and I input the new line to be " 1 2/3/2019 22 11 ". Then when I open the file the record will be the new one.

I'm afraid you will have to re-write the entire file. Read the content of the file line by line, store it in memory (maybe a vector of strings). Now do your editing on the specified line in that vector. When the operation is complete, dump the entire content of vector in another file. You may later replace the original file.

Related

Reading tag from HTML file in c++

I got these questions that I stuck for the past week, "tag always starts with '<' and ends with '>'link always starts with "<a" or "<A" and ends with '>'comment always starts with "<!--" and ends with "- ->",
How can I count these using only while loop or other loops? I'm in the intro programming class, anything beyond loop, if and switch statement is not allowed to use.
Here is the program I done so far and I can't count the the lines and links at the same time, but if I break them apart, I can get the result I want.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inFile;
char ch,
prevchar,
currchar;
int linenum = 0,
tagnum = 0,
commentnum = 0,
linknum = 0,
cfilenum = 0,
ctagnum = 0;
double percent;
string line;
string filename;
cout << "========================================\n";
cout << " HTML File Analyzer\n";
cout << "========================================\n\n";
cout << "Please enter the the file name(no blank): \n";
cin >> filename;
inFile.open(filename.c_str());
while (!inFile)
{
cout << "Please re-enter the file name:\n";
cin >> filename;
inFile.open(filename.c_str());
}
cout << "========================================\n";
cout << " Text of the file \n";
cout << "========================================\n\n";
while (inFile)
{
for (linenum = 0; getline(inFile, line); linenum++);
}
inFile.get(prevchar);
inFile.get(currchar);
while (inFile)
{
if ((prevchar == '<') && (currchar == 'a'))
linknum++;
prevchar = currchar;
inFile.get(currchar);
}
cout << "========================================\n";
cout << " End of the text \n";
cout << "========================================\n\n";
cout << "Analysis of file\n";
cout << "----------------\n\n";
cout << "Number of lines: " << linenum << endl;
cout << "Number of tags: " << tagnum << endl;
cout << "Number of comments: " << commentnum << endl;
cout << "Number of links: " << linknum << endl;
cout << "Number of chars in file: " << cfilenum << endl;
cout << "Number of chars in tags: " << ctagnum << endl;
cout << "Percentage of characters in tags: " << percent << endl;
return 0;
}
After the first loop has finished, your inFile stream is pointing to the end of the file and its eof flag is set.
Issue these statements inbetween your loops to resp. clear the flag and go back to the start of the file:
inFile.clear();
inFile.seekg(0);
That the first statement is not necessary in C++11, but I don't know what environment you are using. Also note that you can do some of the counting operations together in a loop.

C++ Program need help to debug

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct football_game
{
string visit_team;
int home_score;
int visit_score;
};
void printMenu();
int main()
{
int i, totalValues = 0;
ifstream inputFile;
string temp = "";
inputFile.open("games.txt");
if (!inputFile)
{
cout << "Error opening Input file!" << endl;
exit(101);
}
inputFile >> totalValues;
getline(inputFile, temp);
cout << " *** Football Game Scores *** " << endl << endl;
cout << " * Total Number of teams : " << totalValues << endl << endl;
football_game* records = new football_game[totalValues];
// while (!inputFile.eof())
// {// == NULL) {
for (i = 0; i < totalValues; i++)
{
getline(inputFile, records[i].visit_team);
cout << records[i].visit_team << endl;
inputFile >> records[i].home_score >> records[i].visit_score;
cout << records[i].home_score << " " << records[i].visit_score << endl;
getline(inputFile, temp);
}
//}
cout << endl;
int choice = 0;
int avg_home_Score = 0;
int avg_visit_Score = 0;
printMenu(); // prints menu
cout << "Please Enter a choice from the Menu : ";
cin >> choice;
cout << endl << endl;
while (true)
{
switch (choice)
{
case 1:
cout << " Score Table " << endl;
cout << " ***********************" << endl << endl;
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
for (int i = 0; i < totalValues; i++)
{
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|' << setw(7)
<< right << records[i].visit_score << " " << '|' << endl;
}
cout << endl << endl << endl;
break;
case 2:
{
string team_name;
cout << "Enter the Team Name : ";
cin >> team_name;
for (int i = 0; i < totalValues; i++)
{
if (records[i].visit_team == team_name)
{
cout << " VISIT_TEAM"
<< " "
<< " HIGH_SCORE"
<< " "
<< "VISIT_SCORE " << endl;
cout << " -----------"
<< " "
<< "-----------"
<< " "
<< "------------" << endl;
cout << '|' << setw(18) << left << records[i].visit_team << " " << '|'
<< setw(7) << right << records[i].home_score << " " << '|'
<< setw(7) << right << records[i].visit_score << " " << '|'
<< endl;
}
}
cout << endl;
break;
}
case 3:
{
for (int i = 0; i < totalValues; i++)
avg_home_Score += records[i].home_score;
cout << "Average home_score: " << (avg_home_Score / totalValues) << endl << endl;
break;
}
case 4:
{
for (int i = 0; i < totalValues; i++)
avg_visit_Score += records[i].visit_score;
cout << "Average visit_score: " << (avg_visit_Score / totalValues) << endl << endl;
break;
}
default:
{
cout << "Please enter valid input !!" << endl;
break;
}
}
printMenu();
cin >> choice;
}
return 0;
}
void printMenu()
{
cout << " Menu Options " << endl;
cout << " ================ " << endl;
cout << " 1. Print Information of all Games[Table Form] " << endl;
cout << " 2. Print Information of a Specific Game " << endl;
cout << " 3. Print Average points scored by the Home Team during season" << endl;
cout << " 4. Print Average points scored against the Home Team" << endl << endl << endl;
}
Here is the input file i am using
games.txt
5
SD Mines
21 17
Northern State
10 3
BYU
10 21
Creighton
14 7
Sam Houston State
14 24
When i am using the 2nd option (Print Information of a Specific Game) from the output screen,
it ask me to enter the team name and when i enter the team-name.
For example: SD Mines it gives me an error, but when I enter the team-name with no space like: BYU it works fine for me.
cin >> team_name;
Takes the input only upto space.
You might want to use cin.getline() for taking space separated strings as input.
A small program demonstrating the same :
#include <iostream>
#include <string>
int main ()
{
std::string name;
std::cout << "Please, enter your full name: ";
std::getline (std::cin,name);
std::cout << "Name is : , " << name << "!\n";
return 0;
}
std::cin ignores whitespaces by default.
To include spaces in your input try :
getline(cin, team_name);
This would pick up all the characters in a line until you press enter. This is available in
#include<string>
You need to flush the std::cin buffer after reading the choice:
#include <limits>
//...
cin >> choice;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Refer to this question for detailed explanation.
Also, if you want to read strings with spaces from the standard input, replace this:
cin >> team_name;
with this:
getline(cin, team_name);
as already mentioned in other answers. No need to flush std::cin this time, since you have already read the full line.
Finally, remove extra newlines from your games.txt:
5
SD Mines
21 17
Northern State
...

How to use the same letter for an int and cin keyboard input C++

Hi I want to use the same letter for an int and cin keyboard input so when I enter in the new number it changes the number in the cell when I enter the score in with the keyboard sample code take into account i'm still a beginner and still learning:
int h = 0;
cout << " _______________________" << endl;
cout << "|chelsea fc |"<< h << "|" << endl;
cout << "|___________|__________|" << endl;
string h = "";
cout << "Type here to add score to table" << endl;
getline(cin, h);
cout << "You added the score " << h << " to the table" << endl;
If I understand you correctly, you want something like this:
int score = 0;
cout << " _______________________" << endl;
cout << "|chelsea fc |"<< score << "|" << endl;
cout << "|___________|__________|" << endl;
cout << "Type here to add score to table" << endl;
cin >> score;
cout << "You added the score " << score << " to the table" << endl;
Remember that when reading numbers and strings, using the input operator >> reads and discards leading white-space in the input, so even if there is a newline in the input buffer after the input of the score, if you attempt to read a new number or a string that newline will simply be ignored.
Try to write a function that outputs the score table based on an integer. Something like this:
void write_table(int h) {
cout << " _______________________" << endl;
cout << "|chelsea fc |"<< h << "|" << endl;
cout << "|___________|__________|" << endl;
}
Call that function after you ask the user for input.

Replace white space with another character after calling function c++

I need help getting declared string function to change white space of input file to a specific character.
if (infile.fail())
{
cout << "The file doesn't exist";
exit(-1);
}
else
{
numBooks = readFile (infile, magSub, 260);
for (i=0; i<numBooks; i++)
{
cout << "Last Name: " << magSub[i].lastName << endl;
cout << "First Name: " << magSub[i].firstName << endl;
cout << "Street Address: " << magSub[i].address << endl;
cout << "City: " << magSub[i].city << endl;
cout << "State or Province: " << magSub[i].state << endl;
cout << "Country: " << magSub[i].country << endl << endl;
cout << "Zip or Postal Code: " << magSub[i].zip << endl;
cout << "Expiration Date: " << magSub[i].expDate << endl;
cout << "Subscriber Number: " << magSub[i].subNum << endl << endl;
}
writeFile(outfile, magSub, numBooks);
}
}
void fillSpace (string &expDate)
{
for (int i=0; expDate.length(); i++)
{
if (isspace(expDate[i]))
expDate[i] = '0';
}
}
I have the function declared above main. I know I need to call the function but I can't get it to change the white spaces.
In your code for fillSpace, you are not checking for the end of string condition. You should use i<expDate.length() for checking the end of string.
You have missed the check condition in for loop of fillSpace function.
for (int i=0; i < expDate.length(); i++)
And for calling the function
you have to declare a string which will store the string from the magSub[i].expDate.
and then pass that string to the function fillSpace.
After that you will get the string with replaced char space with '0'.
cout << "Expiration Date: " << magSub[i].expDate << endl;
please use the following code:
string temp = magSub[i].expDate; // copy the string to the temp string/char array
fillSpace (temp); // Missing Line for function call
cout << "Expiration Date: " << temp << endl; // replace line with
Hope
this will Help you.

Seemingly simple issue with calling information from an array in C++

This seems like it should be easy, which is why it is driving me especially insane. Hopefully someone out there will see the problem right off. I'm just trying to build arrays from an array built from a user input. It seems to create an array that is bigger than the one I meant for it to. Here's the program:
int main()
{
ifstream inFile;
ofstream outFile;
int numReq, fileSize;
string lang, dash;
char fileName[40];
char confirm[10];
char confirm2[10];
int character;
char year[3];
char month[1];
char day[1];
char hour[1];
cout << "What file to process?" << endl;
cin >> fileName;
year[0] = fileName[14];
year[1] = fileName[15];
year[2] = fileName[16];
year[3] = fileName[17];
cout << "year = " << year << "." << endl;
month[0] = fileName[18];
month[1] = fileName[19];
cout << "month = " << month << "." << endl;
cout << "so I gotta know, what is..." << endl;
cout << "month[0]? " << month[0] << endl;
cout << "month[1]? " << month[1] << endl;
cout << "month[2]? " << month[2] << endl;
cout << "month[3]? " << month[3] << endl;
cout << "month[4]? " << month[4] << endl;
cout << "month[5]? " << month[5] << endl;
cout << "month[6]? " << month[6] << endl;
day[0] = fileName[20];
day[1] = fileName[21];
cout << "day = " << day << "." << endl;
hour[0] = fileName[23];
hour[1] = fileName[24];
cout << "hour = " << hour << "." << endl;
cout << "so, 'fileName[23]' is = " << fileName[23] << "?" << endl;
cin >> confirm;
cout << "So, the year is " << year << ", the month is " << month
<< ", the day is " << day << ", the hour is " << hour << "?" << endl;
cin >> confirm;
//cout << "Is this what you chose? " << fileName << endl;
//cin >> confirm;
//cout << "Which character to manipulate?" << endl;
//cin >> character;
//cout << "This one? " << fileName[character] << endl;
//cin >> confirm2;
inFile.open(fileName);
assert (!inFile.fail());
outFile.open("revisedPracticeFile1.txt");
outFile << fixed << showpoint; // I have no idea what this is...
outFile << setprecision(2); // .. or this for that matter.
cout << "Processing data" << endl;
inFile >> lang;
while (!inFile.eof() ){
if (lang.length() <= 2){
outFile << lang << " ";
// I should keep in mind, that, for whatever reason, it seemed like the
//item 'setw(6)' made the program work when I put it in, but didn't seem
//to make the program stop working when I took it out. Curious..
inFile >> dash >> numReq >> fileSize;
outFile << numReq << " " << fileSize << endl;
}
else{
inFile >> dash >> numReq >> fileSize;
cout << "took out " << lang << " " << numReq << " " << fileSize << endl;
}
inFile >> lang;
}
inFile.close();
//assert(!inFile.fail());
outFile.close();
return 0;
}
...And, this is what happens when I run the program:
What file to process?
projectcounts-20090101-010000
year = 2009.
month = 01009.
so I gotta know, what is...
month[0]? 0
month[1]? 1
month[2]? 0
month[3]? 0
month[4]? 9
month[5]?
month[6]?
day = 011009.
hour = 0111009.
so, 'fileName[23]' is = 0?
yes
So, the year is 1009, the month is 11009, the day is 111009, the hour is 0111009?
^C
... So what gives?
The syntax char year[3]; declares an array with 3 element. But, then you use it to store 4 elements. There are similar issues with your other arrays.
Also, you're using char arrays as strings. That's a C (not C++) way to do things. Of course you're allowed to do this if you want. But, these c-style strings use the convention that the last item is a zero.
Thus, if you wanted a C-style string to store the work 'foo', you could do it like this
char string[10]; // anything bigger than 3 works
string[0] = 'f';
string[1] = 'o';
string[2] = 'o';
string[3] = '\0'; // this zero tells functions like `printf` that the string has ended.
Without that last zero, functions like printf will just keep outputting memory locations until it happens upon a zero somewhere.
EDIT: Consider using c++ std::string for your string processing.