Sam64710
Sam64710

Reputation: 23

Taking Input to Arrays Issue

I'm creating a console timetable application in which you can create a timetable, change it, and delete it. I'm on the stage of taking the input for the calculator. However, when I run the code, as soon as I finish taking the input, the window just closes. Here is the code:

int input()
{
    int numberOfElements;
    cout << "How many items do you want in your timetable? ";
    cin >> numberOfElements;
    char* itemArray[numberOfElements] = {};
    for (int i = 1; i <= numberOfElements; i++)
    {
        cout << "Please enter a session: ";
        cin >> itemArray[i];
    }
    for (int i = 0; i < numberOfElements; i++)
    {
        cout << itemArray[i] << "\n";
    }
    return 0;
}

There is some code in the main function as well, but it's irrelevant (only to find out for what day it is). I want you to have a look at the first for loop in the code, where I take in input. When running this code (in a separate window altogether), it closes as soon as I give in the input. Even if I say that I want 3 sessions (or any number), it closes right after I input the first session. In case you were wondering, I already tried replacing

char* itemArray[numberOfElements] = {};

with

char* itemArray[numberOfElements];

Just in case it's useful to anyone, I'm using the MinGW compiler.

Thanks.

Upvotes: 0

Views: 57

Answers (1)

user12002570
user12002570

Reputation: 1

In Standard C++ the size of an array must be a compile time constant. So take for example the following statements in your program:

int numberOfElements;
cout << "How many items do you want in your timetable? ";
cin >> numberOfElements;
char* itemArray[numberOfElements] = {};//not standard C++

The statement char* itemArray[numberOfElements] = {}; is not standard C++ because numberOfElements is not a constant expression.

Additionally, you're going out of bounds of the array because of the <= in the for loop instead of <. This leads to undefined behavior.

Better would be to use std::vector<std::string> as shown below:

#include <iostream>
#include<vector>
#include <string>
int main()
{
   
    int numberOfElements;
    std::cout << "How many items do you want in your timetable? ";
    std::cin >> numberOfElements;
    std::vector<std::string> arr(numberOfElements); //create vector of size numberOfElements
    for (std::string &element: arr)
    {
        std::cout << "Please enter the element: ";
        std::cin >> element;
    }
    for (const std::string& element: arr)
    {
        std::cout << element << "\n";
    }

}

Demo.

Upvotes: 1

Related Questions