Reputation: 39
How would I go about reading numbers from a text file and adding them to an array?
textfile: HEAPinput2.txt
12
9
10
11
12
2
4
6
5
3
1
7
8
What I have here is a snippet of my code. If needed I will provide my whole main. But essentially I have a switch statement, when user chooses R read from a file and sort them into the array. I've been looking online and have been seeing different ways of doing it, I have done it as shown below, but have been running into some errors
case 'R':
file.open("<path of HEAPinput>");
if(!file){
cout<<"There was a problem opening file HEAPinput2.txt for reading";
exit(0);
}
else{
int count = 0;
std:: int count;
while(file>>count){
count++; //making sure it increments the
}
elme = *new ELEMENT[count];
cout<<count; //prints out 8 for some reason
}
break;
Upvotes: 0
Views: 1023
Reputation: 73637
Assuming that the first integer of the text file is the number of remaining integers to be read, and that elme
is an int*
, and that you are not allowed for this exercise to use vectors:
else{
int count = 0; // this should REALLY be declared in same block as elme
int i=0;
if(file>>count) {
elme = new int[count]; // assuming that count is valid and not 0
while (i<count && file>>elme[i])
i++;
count = i; // to adjust the number of items to the number really read
}
cout<<count;
}
break;
If you're allowed to use vectors, then go to Paul Sander's answer because vector is really century XXI for C++, whereas dynamically allocated arrays are something like the medieval age.
Upvotes: 0
Reputation: 25418
To sum up what others have said, this is extremely easy with std::vector
:
#include <vector>
#include <fstream>
#include <iostream>
int main ()
{
std::ifstream file;
file.open ("<path of HEAPinput>");
if(!file)
{
std::cout << "There was a problem opening file HEAPinput2.txt for reading";
exit (0);
}
std::vector <int> v;
int i;
while (file >> i)
v.push_back (i);
file.close ();
}
More details on std::vector
here:
https://en.cppreference.com/w/cpp/container/vector
Upvotes: 1