0

Currently, I have a main menu that allows users to select options and one of the options is to allow users to enter a file name.

If I have four files:

a.txt
b.txt
c.txt
d.txt

Currently, my .h file is as such

#ifndef WEATHERSYSTEM_H
#define WEATHERSYSTEMs_H

#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h> 
#include <iomanip>

using namespace std;

void readconfigfile(string filename, int & xIdx, int & yIdx, string toAccessFiles[], int**& idsArr, string**& namesArr, int** & ccGrid, int** & pGrid);

#endif

and my .cpp file is as such

#include "weathersystem.h"
using namespace std;

int main(int argc, char* argv[])
{
/*Variables declaration*/
char choice = ' ';
int gridXIdxMax = -1;       //colcount
int gridYIdxMax = -1;       //rowcount
string toAccessFile[3];

int** idsGrid = NULL;
string** namesGrid = NULL;
int** ccGrid = NULL;
int** pressureGrid = NULL;

while (1)
{
    mainmenu();
    cin>>choice;
    cout<< endl;

    if (choice == '1'){
        string filename;
        cout<<"[Read in and process a configuration file]"<<endl;
    cout<<"Please enter filename: ";
    cin>>filename;
    readconfigfile(filename, gridXIdxMax, gridYIdxMax, toAccessFile, idsGrid, namesGrid, ccGrid, pressureGrid);
    cout << endl;
    cin.clear();
}

What I am unclear is in my .cpp file if I have 4 files, do I have to declare string toAccessFile[3] or [4] in my .cpp file. As currently, the code works even when it is toAccessFile[3].

  • Accessing out-of-range of arrays invokes *undefined behavior*. Anything is allowed to happen when *undefined behavior* is invoked. It need not lead to crash. – MikeCAT Jan 12 '21 at 18:29
  • Probably a transcription error, but if not the extra `s` in `WEATHERSYSTEMs_H` could wreak havoc. – user4581301 Jan 12 '21 at 18:49

1 Answers1

0

If you have 4 files you should declare the space for all of them. So in your case [4]. Otherwise you may have undefined behaviour (anything can happen). Have a look here: Accessing an array out of bounds gives no error, why?

But as it seems to be dynamic (means you are not fixed to have a maximum of 4 files) you should consider a dynamic container. std::vectorstd::string is one commonly used, read here for more information.

If you have a satic size you also should consider to use std::array (see here) which is also more C++ like and provides additional features like a size() method.