2

I just want the user to enter some numbers. If the number is -1 the program stops and then outputs those same numbers. Why is that so difficult? I don't understand why the logic is not working here.

For example when the user types:

1 2 3 -1 

The program should then print out: 1 2 3 -1

#include <iostream>

using namespace std;

int main()
{
    int input, index=0;
    int array[200];

    do
    {
        cin >> input;
        array[index++]=input;
    } while(input>0);

    for(int i=0; i < index; i++)
    {
        cout << array[index] << endl;
    }
}
4

1 回答 1

6

改变这个

for(int i=0; i < index; i++)
{
    cout << array[index] << endl;
}

for(int i=0; i < index; i++)
{
    cout << array[i] << endl;
}

index在 seconde 循环中使用,导致您的程序在用户输入后打印所有数组单元格。

另外,如果-1您的情况是,您应该将其更改为

} while(input>=0);
             ^^ 

否则,也0将停止循环,这不是您所要求的。

于 2013-07-28T00:40:17.090 回答