I want to know how to wrtie a code to read a file "abc.txt" and read the integer and count how many integer inside the file.
And place the data, to from a array.[the length and the list]
#include <iostream>
#include <fstream>
#include <vector>
usingnamespace std;
int main() {
//Create a dynamic array to hold the values
vector<int> numbers;
//Create an input file stream
ifstream in("abc.txt",ios::in);
/*
As long as we haven't reached the end of the file, keep reading entries.
*/
int number; //Variable to hold each number as it is read
//Read number using the extraction (>>) operator
while (in >> number) {
//Add the number to the end of the array
numbers.push_back(number);
}
//Close the file stream
in.close();
/*
Now, the vector<int> object "numbers" contains both the array of numbers,
and its length (the number count from the file).
*/
//Display the numbers
cout << "Numbers:\n";
for (int i=0; i<numbers.size(); i++) {
cout << numbers[i] << '\n';
}
cin.get(); //Keep program open until "enter" is pressed
return 0;
}
This may end up being different, if your input file is different than I assumed - for example, if your numbers are separated by commas, you'd need to go about it differently.
Can we do this without using the dynamic array ?
And since I need to pass the length of the array and the content (number) to calculate the average value of the array.
You could move the file pointer to the EOF(end of file) and return its position (in bytes)...
But that would defeat the "dynamic" array purpose again, because u would have to use "new"...
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
usingnamespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
all you have to do is change "cout << line << endl;" to stick line into a string array, and then increment the index. eg.
1 2 3 4 5 6
int index = 0;
while (! myfile.eof() )
{
getline (myfile,line);
myArray[index++] << line;
}
however files can be different number of lines, so what you can do is increment the actual size of the array as you go by declaring temp as the current index size +1, using a for loop copy all elements over, and then do the same with the array. This is a very bulky way of doing things, but if your coding for class, you don't have much of a choice. Otherwise vectors are the way to go.