0

im about to code a small application for myself. I have a code prepared. It looks something like this.

ifstream file("input.txt");

if (file.is_open())
{
    string myArray[5];

    for (int i = 0; i < 5; ++i)
    {
        file >> myArray[i];
    }

    cout << myArray;
}

Can somebody say how to get the words from the input.txt into an array? (Content of my txt file: "Bla Bla Bla") but the array just contains random numbers..

Kind regards

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • `cout << myArray;` won't work. You'll need to iterate through the items in the array and output them one by one, similar to how you input them from the file. – Retired Ninja Jun 14 '21 at 09:15

1 Answers1

2

When you call

std::cout << myArray;

array to pointer conversion takes place, and you print the address of your myArray first element. If you want to print 5 elements of your std::string array, just iterate over them like before when reading the file:

    for (int i = 0; i < 5; ++i)
    {
        std::cout << myArray[i] << std::endl;
    }

also range loop will work here:

    for (const auto& str : myArray)
    {
        std::cout << str << std::endl;
    }
pptaszni
  • 5,591
  • 5
  • 27
  • 43