Loading from a textfile and filling a vector

When i use this code to load the textfile into the vector and I am going to print it, it seems like the vector is filled with the same name and number several times. I want to open a file and edit the file. Add new names and numbers. Delete maybe and save it so I can use it again.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  case 5:
{ 
	ifstream fin("Phonebook.txt");

	string name;
	int number;

	while(fin >> name >> number) 
	{
		myPhonebook.push_back(Phonebook(name, number));
	}

	cout << name << number << "\n";
}
break;
Tip: When you write code ALWAYS put them into functions and then call that function. It makes it easier to debug the problem.

What you are trying to do utilizes three functions. Read, Write, Delete.

This is my function that I created to read a dvd list into a vector:
1
2
3
4
5
6
7
8
9
10
11
void read_dvds(string dvd_file_name, vector<Dvd> &my_dvds)
{
	ifstream fin(dvd_file_name);
	while (!fin.eof())//The file is still open
	{
		Dvd *temp_dvd = new Dvd;//Pointer is pointing to created object
		fin >> *temp_dvd;//The file is read into that object
		my_dvds.push_back(*temp_dvd);//The data is pushed into the vector
		delete temp_dvd;//The object is deleted. Otherwise it would take up too much space on your computer. 
	}
}


Warning!!: This was created using DVD as a CLASS and the >> operators were overloaded. This is just to give you an idea on what to research/look for. Vectors, overloaders, pointers, file open and close operations.
You need to include a read in statement at the end of your while loop for it to continue reading data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  case 5:
{ 
	ifstream fin("Phonebook.txt");
	string name;
	int number;

	while(fin) // while there is data in file
	{
                fin >> name >> number;
		myPhonebook.push_back(Phonebook(name, number));
                fin >> name; // read in the next name
	}

	cout << name << number << "\n";
}
break;


My suggestion is probably bad, I'm a C++ beginner.
Last edited on
Both Momothegreat and specter113 are making bad suggestions. Your code for reading the file is fine the way it is, however I believe you probably want to clear the vector contents before reading all values into it again. As it is, you are just adding to the vector the contents that are probably already contained in it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
   case 5:
   { 
      std::ifstream fin("Phonebook.txt");

      if (!fin.is_open()) 
      {
           std::cerr << "Unable to open file \"Phonebook.txt\"\n";
           break;
      }

      string name;
      int number;

      myPhonebook.clear();    // clear the contents of myPhonebook
      while(fin >> name >> number) 
         myPhonebook.push_back(Phonebook(name, number));

      // cout << name << number << "\n";
   }
   break;
Topic archived. No new replies allowed.