for-loop with user defined array - C ++

时间:2015-10-15 02:37:13

标签: c++ arrays pointers for-loop

我当前的项目假设为参与者整数)和新参与者整数>获取用户输入),为各个输入定义一个数组(参与者 参与者),然后循环遍历代码,询问参与者或新参与者的姓名。虽然,在我的第一个for循环(如果我的代码到达那里,第二个),它首先要求"名称#1:" ,然后输入开始非常糟糕并退出程序。我认为问题在于指针,但这是我的代码:

#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;
}

2 个答案:

答案 0 :(得分:1)

除非你的所有学生都是秘密特工,或者生活在THX-1138的世界,否则他们有名字,而不是数字。更改存储名称的类型。

您遇到的问题是,您希望从cin读取一个整数,但是您要为其提供文字。这会设置流上的错误位,因此之后的所有后续输入都将失败,直到重置为止。

答案 1 :(得分:0)

首先,使用

cin >> variable
在C ++中不推荐使用

。使用getline()会好得多;功能。这里有一个很好的描述:

http://www.cplusplus.com/forum/articles/6046/

您还应该将从getline()接收的输入输入到整数。