i have the integers 100 5 5 9 in my array numbers.But when i compile this program i get 2009312941!! Please help me

int main()
{ 	   
   	
   int numbers[4];
   int i;
    
    ifstream streamin;
   
    
   
    streamin.open("input.txt");
    for(i=0;i<4;i++)
   	{streamin >>  numbers[i] ;
        
    }
    cout << numbers[i];
    streamin.close();

Dani AI

Generated

The program prints a seemingly random large number because it reads four integers into indices 0..3, then tries to print numbers[i] after the read loop — at that point i is 4, so numbers[4] is out of bounds. Accessing an element past the end of a C-style array is undefined behavior, which explains the garbage value. and were pointing toward the same root cause: the loop increments i past the last valid index before the loop stops.

A safer, modern approach is to read into a container and print only the values actually read. This example uses std::vector and checks the file open/read:

#include <iostream>
#include <fstream>
#include <vector>

int main() {
    std::ifstream in("input.txt");
    if (!in) { std::cerr << "Cannot open input.txt\n"; return 1; }

    std::vector<int> numbers;
    int value;
    while (in >> value) numbers.push_back(value);

    for (std::size_t k = 0; k < numbers.size(); ++k)
        std::cout << numbers[k] << ' ';
    std::cout << '\n';
}

If you must use a fixed array, keep a counter of successful reads and print only that many elements. For example, read into numbers[count] while count < N and increment count on success; then loop k = 0..count-1 to display values. Extra tips: check that the file opened (if (!in)), check each extraction succeeded, compile with warnings enabled (e.g. -Wall -Wextra), and consider printing values as you read them if you only need to display them. These practices avoid out-of-bounds access and the unpredictable output it produces.

Recommended Answers

All 3 Replies

int main()
{ 	   
   	
   int numbers[4];
   int i;
    
    ifstream streamin;
   
    streamin.open("input.txt");
    for(i=0;i<4;i++)
    {
       streamin >>  numbers[i] ;
    }

    // what is the value of i at this point?
    cout << numbers[i];

    streamin.close();
}

i think i=3 at that line..:-/

Look at the for loop's condition
for(i=0;i<4;i++)
i.e. "i" is not less than four at that line.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.