I've attempted to improve the code. I've detailed the changes below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <fstream>
#include <string>
#include <limits>
using namespace std;
void read()
{
ifstream rF("tabel.txt");
string s;
while(getline(rF,s)) {
cout << s << endl;
}
}
void add(const string &name, int id)
{
ofstream sF("tabel.txt", ios::out | ios::app);
sF << name << '\t' << id << endl;
}
int main()
{
string name;
int id, choice;
cout << "To add data press 1 " << endl;
cout << "To read data press 2" << endl;
cout << "Yours choice is" << endl;
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (choice == 1) {
cout << "Start" << endl;
getline(cin, name);
cin >> id;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
add(name, id);
}
else if (choice == 2) {
cout << "Reading..." << endl;
read();
}
else cout << "Not included" << endl;
return 0;
}
|
First thing is your declaration of your main function. I have changed it to return int and at the end it returns 0.
On line 9 I have gotten rid of the
ios::app
argument you're passing to the ifstream constructor. ios::app is what you use for an ofstream when you want to place the put pointer at the end of the file for appending data to the end of the file.
I've changed your add function to take an std::string instead of char[100] because there's no point in mixing the string class and C style strings in the same code. It is const because you won't be making any changes to it and it is a reference (&) because there is no point constructing a new string when you pass it to the function.
I've also changed the way your construct your ofstream on line 19:
ofstream sF("tabel.txt", ios::out | ios::app);
When you are passing flags into the constructor of an ifstream/ofstream, you need to also pass either ios::in or ios::out depending on which it is. This is done by bitwise ORing them together. For example (because they're actually not), say ios::out was represented by 1 (0001) and ios::app was represented by 2 (0010) when you bitwise OR them together if either of the corresponding bits in either of them is a 1, then the resulting bit becomes a 1. So:
0001
0010
=
0011
And that is how it works.
In main I have changed name to an std::string, and I've also added this code:
cin.ignore(numeric_limits<streamsize>::max(), '\n');
after each time you've used operator>>. This is to empty the buffer in case any characters have been left in it.
I've also got rid of your switch as there wasn't much need for it really and I've just rearranged your code a little bit. Not sure what the for loop was for with case 1 but I got rid of that. The code now compiles and works just fine.