I was working on the being of a cash register and I was testing this portion of my code. It compiles, but when I input my first items name I get a windows error and the program ends. I would appreciate any help an/or explanation.

#include <iostream> // allows output and input
#include <iomanip>  //allows i/o manipulation
#include <stdlib.h>
#include <fstream>  // allows file i/o
#include <string>   // allows the use of strings


//declares variables
int current_input_number;
int number_of_items;    




main()
{
    using namespace std;

    system("COLOR 0a"); // changes color 
    
    //declares an array of strings    
    string item_name[number_of_items];
    
    cout << "How many items does the customer have? \n";
    cin >> number_of_items;
    
    
    for (current_input_number = 1; current_input_number < number_of_items; current_input_number++)
    {
        cout << "Please enter product number " << current_input_number << '\n';
       cin >> item_name[current_input_number];   
        
    }
    
    for (current_input_number = 1; current_input_number < number_of_items; current_input_number++)
    {
      cout << item_name[current_input_number] << '\n';   
        
    }
    

    cin.ignore(2);
    return 0;
}
int number_of_items;    

main()
{
    //declares an array of strings    
    string item_name[number_of_items];
    
    cout << "How many items does the customer have? \n";
    cin >> number_of_items;

When you use number_of_items, what value does it have? How large is the array?

declares an array of strings    
    string item_name[number_of_items];
    
    cout << "How many items does the customer have? \n";
    cin >> number_of_items;

When specifying the size of an array in the declaration like that on line 22, the value of number_of_items must be known at compile time (unless you have certain language extensions on when you are compiling, but that runs the risk of your code being non-standard).
You have double trouble because even if it were legal, you declare the array to be that size before the user gets to input a value.

Your best bet is to prompt the user for input but then create the array dynamically. So scratch line 22 and around 26 put in a: string * item_name = new string[current_input_number]; Check your for loops also: remember that arrays are 0 based.

EDIT: Sorry I stole the thunder of your teaching moment WaltP

Edited 6 Years Ago by jonsca: n/a

thank you. I have not studied dynamic arrays yet, but I will do that

This question has already been answered. Start a new discussion instead.