开发者

Loop asking user for input into an array

You all have helped me so much in the past, I am coming back for more help!

I am working on another C++ assignment for school. I have to collect 20 numbers between 10 and 100 from the user and compare them all and print out the ones that are not duplicates.

The part I am stuck on is trying to get the user input to loop until I have all 20 numbers. What I have makes sense to me, but it apparently is not working. Sorry for the ridiculous comments, I have to comment everything for class.

Any light you can shed on my goof up would be amazing! Thank you so much!

int FindDuplicates[20]; // my little array
int UserInput; // the number from the user to compare
int count; // the number of numbers entered

for(count=0; count<FindDuplicates; count++;) // what I am trying to do is have count start at 0. as long as it is less than the max array, add 1 to the count
{
    cout << "Please enter a number between 10 and 100: "; // print out what I would like
    cin >> UserInput开发者_JAVA技巧; // get the number from the user
}


your problem is how to enter 20 valid numbers, is it? I think the do while loop will help you.

int FindDuplicates[20]; // my little array
int UserInput; // the number from the user to compare
int count = 0; // the number of numbers entered

do
{
    cout << "Please enter a number between 10 and 100: "; // print out what I would like
    cin >> UserInput; // get the number from the user

    if (UserInput >= 10 && UserInput <= 100)
    count++;
} while (count < 20);

Hope that will help you.


for( int count = 0; count < 20; count++ )
{
    cout << "Please enter a number between 10 and 100: ";
    cin >> userInput;

    FindDuplicates[ count ] = userInput;
}

You can also check for valid input with:

while( UserInput < 10 || UserInput > 100 )
{
    cout << "Please enter a number between 10 and 100: ";
    cin >> UserInput;
}

If you do that just make sure you have initialized UserInput to something. So:

int FindDuplicates[ 20 ];
int UserInput = 0;
int count = 0;

//count has already been defined, so no need to do it again
for( ; count < 20; count++ )
{
    //Keep asking until valid input is given
    while( UserInput < 10 || UserInput > 100 )
    {
        cout << "Please enter a number between 10 and 100: ";
        cin >> userInput;
    }

    //Add userInput into the array
    FindDuplicates[ count ] = UserInput;
}


FindDuplicates will give you the pointer pointed to the array (see this), not the size. You should use

for(count=0; count<20; count++;)

instead.


There is a syntax error on the line below, check how for statements work. There's also a problem with the <FindDuplicates. Make sure you understand what that variable means.

for(count=0; count<FindDuplicates; count++;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜