简体   繁体   English

C ++:存储用户输入

[英]C++: Storing user inputs

I just want the user to enter some numbers. 我只希望用户输入一些数字。 If the number is -1 the program stops and then outputs those same numbers. 如果数字为-1,程序将停止,然后输出相同的数字。 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 然后,程序应打印出: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;
    }
}

Change this 改变这个

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

To

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

You used index at the seconde loop causing your program to print all the array cell's after the user input. 您在第二个循环上使用了index ,导致您的程序在用户输入打印所有数组单元格。

Also, if -1 is your condition you should change it to 另外,如果您的条件是-1 ,则应将其更改为

} while(input>=0);
             ^^ 

Otherwise, also 0 will stop the loop, which is not what you asking for. 否则, 0也将停止循环,这不是您要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM