I am writing an eVoting program the addTally function adds 1 to the Candidate's voting tally when called and prints it back to the file from where it took the input replacing the old text.
Now, I have no idea why im getting an error when running this program. Whenever i comment out the output file in addTally Function including where its used, it works. Any ideas please?
Don't use two objects on the same file, you will have concurrency problems. Instead, use a single object and read/write that.
You should realise that you can't edit lines in a text files like that as changing the length of lines overwrites the following line. You can only treat binary files in that way.
If you want to update the text file, you need to read the content into memory, make your amendments, then rewrite the entire file.
I tried ios::in | ios::out in an object to read and write in a file but still it wont work.
I'm not changing any text in a file, as you said, i am copying the content into array, amending it and then rewriting the whole content of the file. Still its not working
void addTally(char choice)
{
fstream File("Candidates.txt", ios::in | ios::out);
string Data_Line;
vector <string> Candidates;
string C_name[5];
int Tally[5];
while(getline(File, Data_Line)) //Store data read from 'inCandidate' in 'Data_Line' while "std::getline()" returns true.
{
Candidates.push_back(Data_Line); //Creates a TEMPORARY object that std::vector.push_back then uses the default copy operator to create and store an instance from.
cout << Data_Line <<endl;
}
for (int i = 0; i < 2; i++)
{
stringstream ss(Candidates[i]);
ss >> C_name[i] >> Tally[i];
cout << Tally[i] << endl;
}
switch (choice) {
case'1':
Tally[0]++;
File << C_name[0] << " " << Tally[0] << endl;
File << C_name[1] << " " << Tally[1] << endl;
break;
case'2':
Tally[1]++;
File << C_name[0] << " " << Tally[0] << endl;
File << C_name[1] << " " << Tally[1] << endl;
default:
break;
}
File.close();
}
It shows the following code when i run the program. I guess its from somewhere in C++ library. If you understand, it might help... It highlights __str_ = __s;