Hello all. I am trying to read numbers from a file and put them into an area , that has a max size of 100 elements. (making the numbers up in the file) and I wanna print out the last number in that file. So say the file has the numbers
1 2 3 4, I am trying to print out 4 I am getting a number in the thousands and was wondering if anyone can point me into the direction of where I am going wrong
#include <iostream>
#include <fstream>
#include <iomanip>
usingnamespace std;
int main()
//declaring variables
{
int arr[100]; //initializing an array of 100 elements
int n = sizeof(arr) / sizeof(arr[0]);
int l = arr[n - 1];
string filename;
ifstream file;
cout<<"Input File Name";
cin>>filename;
file.open(filename.c_str());
for(int i=0; i<=100; i++)
{
file>>arr[i]; //puting numbers from file into array
}
cout<<"last number is "<<l<<endl; //printing out last element
}
Because you are using the value "l", which is initialized to a garbage value.
Secondly, you have a buffer overflow in your loop because you are accessing arr[100], which doesn't exist. Remember, if you declare an array with 100 elements, the indexes go from 0 to 99.
If you want to print out the last number, just print arr[99].
I am trying to print out 4 I am getting a number in the thousands
Your compiler, if properly configured, should be warning you about using uninitialized variables.
You really should start getting used to declaring variables close to first use instead of in one big glob at the beginning of some scope. Also use meaningful variable names, and avoid the single letter variables I, O, l as they can be hard to distinguish from the decimal numbers 1 and 0.
#include <iostream>
#include <fstream>
#include <iomanip>
usingnamespace std;
int main()
{
constint ARRAY_SIZE = 100; // Use a compile time constant instead of a magic number.
int arr[ARRAY_SIZE];
string filename;
cout << "Input File Name: ";
cin >> filename;
ifstream file(filename); // Prefer to use the constructor to open files, and with modern C++ no need to convert to a c-string.
int i = 0; // Be sure to initialize variables before you try to use them.
while(i < ARRAY_SIZE && file >> arr[i]) // You're using horrible arrays so make sure you don't overflow your array bounds.
{
++i;
}
int last = arr[i];
cout << "last number is " << last << endl; //printing out last element
// Or just printout the last entry directly without a "temporary" variable.
cout << "Last number is: " << arr[i] << endl;
}