Enthused Binary
Enthused Binary

Reputation: 64

for-loop with user defined array - C++

My current projects is suppose to get user input for participants (integer) and new participants (integer ), define an array for individual inputs (participants and new participants), then loop through code asking for the name of the participant or new participant. Though, in my first for-loop (And second if my code would reach there) it starts by asking "Name #1:" , then after input starts bugging out very bad and exits program. I think the problem is in the pointers, but here is my code:

#include<iostream>

using namespace std;

int main()

{

int dV = 1;

int students;
int newStud;

cout << "Enter number of participants : ";
cin >> students;
system("CLS");

cout << "Please enter the number of new participants: ";
cin >> newStud;
system("CLS");

while(newStud > students)
{
    cout << "You entered a number greater than the overall participants!" << endl << endl;
    cout << "Please enter the number of new participants: ";
    cin >> newStud;
    system("CLS");
}

int *pointer1 = new int[students]; //Pointer to an array of size students(Variable)
int *pointer2 = new int[newStud]; //Pointer to an array of size newStud(Variable)


for (int i = 0; i < students; i++)
{
    cout << "Name #" << dV << ": ";
    cin >> pointer1[i]; //ERROR HERE: After first input, program text blinks a few times then exits     
    system("PAUSE"); //Used for debugging
    system("CLS"); 
    dV++;
}

for (int i = 0; i < newStud; i++)
{
    cout << "New name #" << dV << ": ";
    cin >> pointer2[i];
    system("CLS");
    dV++;

}
return 0;
}

Upvotes: 0

Views: 602

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32727

Unless all your students are secret agents, or live in the world of THX-1138, they have names, not numbers. Change the type you store the names in.

The problem you're seeing is that you want to read an integer from cin but you're giving it text. This sets the error bit on the stream, so all subsequent inputs after that will fail until it is reset.

Upvotes: 1

Related Questions