mercredi 16 octobre 2019

Clion: C++11 code will not print out array[i] unless there's endl at the end of code

In my code, I supposed to have a function where it reads from a file and stores each line of the file to a section of an array. The movie titles go into the titel[] array while the year gets read into the year[] array. **MAIN PROBLEM:**The problem I'm having is in case 2: It will not print out the title[k]. Note: This is a lab assignment so I'm limited to what we've covered so far in class which doesn't include vectors at the moment.

I've tested out printing out title[k] by itself but it will only print out the movie titles if I code it in the following format. cout << title[k] << endl; Otherwise if I just put: cout << title[k]; It will not print out the movie titles, the indentation here might be a bit off, wasn't sure how to fix it.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

void readFiles(string title[], string year[], int MAXSIZE, int &size);
ifstream inFile("movies.txt");

int main()
{
  int menu, b = 0;
  bool loop = true;
  const int MAXSIZE = 100;
  enter code here`string title[MAXSIZE];
  string year[MAXSIZE];
  int size = 0;

  while(loop)
  {
    cout << "Please selection an option from the menu:\n";
    cout << "1. Read in Movies\n";
    cout << "2. List titles, years to the screen\n";
    cout << "3. List titles, year to a file\n";
    cout << "4. Exit\n";
    cin >> menu;
    switch (menu)
    {
        case 1:
            cout << "Reading movies:\n";
            readFiles(title, year, MAXSIZE, size);
            for (int i=0; i < size; i++)
            {
                cout << title[i] << endl;
                cout << year[i] << endl;
            }
            break;
        case 2:
        {
            cout << "List of movies:\n";
            readFiles(title, year, MAXSIZE, size);
            for (int k = 0; k < size ; ++k)
            {
                cout << title[k] << ", " << year[k] << endl;
            }
        }
            break;
        case 3:
        {
            cout << "Writing list of movies to file: ";
            ofstream outfile;
            outfile.open("movies.txt");
            for (int j = 0; j < size; ++j) {
                outfile << title[j];
            }
            outfile.close();
        }
            break;
        case 4:
        {
            loop = false;
        }
    }

}

return 0;
}

void readFiles(string title[], string year[], int MAXSIZE, int &size)
{
    string movie, release;

  while (getline(inFile, movie))
   {
     if (size < MAXSIZE)
      {
        title[size] = movie;
      }
     else if (size > MAXSIZE)
      {
        break;
      }
    getline(inFile, release);
    year[size] = release;
    size++;
}
}

The expected result should be:

The Wizard of Oz, 1939

Deadpool, 2016

Instead, I'm getting:

, 1939

, 2016

Aucun commentaire:

Enregistrer un commentaire