Always make variables as local as possible. C++ allows you to define loop variables within the loop
for(int i = 0; i < SIZE; i++)
{
...
}
// i no longer in scope
so that they fall out of scope at the end of the loop, which is as local as it gets.
Doing this will reveal that you are currently using i
for accessing the array after the loop, at which point i
has the value SIZE
, resulting in an access out of bounds. (Remember, arrays have the indexes 0..SIZE-1
.)
I have no idea what the final line in your program
cout << fruity[i] << endl;
is supposed to do, but if you want to output the array's conetent (as other answers suggest), you will indeed need another loop.
Other, more minor points:
We don't really know what string class you are using, because you omitted the std::
prefix. (The same goes for all the other identifiers from the std library you are using.) I disapprove of that.
The correct type for array indexes is std::size_t
.
The std::endl
manipulator will insert a '\n'
into an output stream and flush the stream's buffer. In an interactive console program as yours is this usually doesn't do any harm. Remember it, though, as flushing the buffer prematurely might considerably slow down a program. (I have seen a case were a program writing a lot of data into a file stream in trickles of a couple of bytes was slowed down by an order of magnitude due to this.) In your case, flushing the output stream#s buffer manually is never really necessary. (Of course, you do want your prompts to appear before you read from the input stream, but this is achieved by std::cout
being tied to std::cin
by default, making std::cout
flush whenever the program attempts to read from std::cin
.)
The program, as I would write it, would look like this:
// Beware, brain-compiled code ahead!
#include <string>
#include <iostream>
int main()
{
const std::size_t size = 5;
std::string fruity[size];
std::cout << "Enter the names of five kinds of fruit:" << '\n';
for(std::size_t i = 0; i < size; ++i)
{
std::cout << "Enter Name of Fruit" << '\n';
std::getline(std::cin, fruity[i]);
}
for(std::size_t i = 0; i < size; ++i)
{
std::cout << fruity[i] << `\n`;
}
return 0;
}