-3

The loop is supposed to ask for the name, year and address of three persons. After the input of the third name, the execution of the program ends and I'm not able to enter the last year and address.

#include <iostream>

int main(){

    std::string Names[2]={};
    unsigned int Years[2]={};
    std::string Address[2]={};
    for(int i=0;i<=2;i++){
        std::cout<<"Enter name >> ";
        std::cin>>Names[i];
        std::cout<<"Enter year >> ";
        std::cin>>Years[i];
        std::cout<<"Enter address >> ";
        std::cin>>Address[i];
    }
    return 0;
}
Hibou
  • 196
  • 2
  • 3
  • 10
  • 8
    Why are your arrays only two elements long? They can't hold three elements... – Max Langhof Oct 22 '19 at 16:25
  • Make the size of your array 3 so it can hold 3 people. –  Oct 22 '19 at 16:26
  • 1
    Your arrays are of size `2`. You should not be asked to enter a third name. That you are means your loop condition is wrong. You should look there. – NathanOliver Oct 22 '19 at 16:26
  • Related: [https://stackoverflow.com/questions/58506897/index-size-of-an-array](https://stackoverflow.com/questions/58506897/index-size-of-an-array) – drescherjm Oct 22 '19 at 16:30
  • Also see https://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c (but really you need a struct, std::vector, and a helper function to read in the value. Use < instead of <= so you get correct zero based size comparisons. And don't write 2 when you mean 3 :) – Kenny Ostrom Oct 22 '19 at 16:35
  • 1
    Suggestion. Rather than three arrays, aggregate the information into a data structure and store a single array of this structure. This often results in less book-keeping overhead and tends to be much easier to sort. – user4581301 Oct 22 '19 at 16:54

3 Answers3

4

Make the size of the array as 3, the index goes from 0-2 e.g.

std::string Names[3]={};
PraveenB
  • 1,270
  • 10
  • 11
2

You need to declare your array with size of 3,as we know an array size like 2 have a number of address that goes from 0 to size-1. In you case your arrays goes from 0 to 1,if you want to insert 3 people you need use 3 as size of your array in this way you have address 0,1 and 2 to use.

std::string Names[3]={};
unsigned int Years[3]={};
std::string Address[3]={};
for(int i=0;i<=2;i++){
    std::cout<<"Enter name >> ";
    std::cin>>Names[i];
    std::cout<<"Enter year >> ";
    std::cin>>Years[i];
    std::cout<<"Enter address >> ";
    std::cin>>Address[i];
}

In this way you solve the problem

  • It is dangerous to use the same constant in four different places, unless you define it once. Especially if 2 and 3 are the same number (in different contexts). – Kenny Ostrom Oct 22 '19 at 16:38
1

the problem is the array size is just 2 and you entered a value to array[3] which never exist

alabdaly891
  • 159
  • 1
  • 8