简体   繁体   English

如何在数组中搜索先前已经输入的int值

[英]How to search an array for an int value that has already been entered previously

I'm making a simple guessing game program. 我正在制作一个简单的猜谜游戏程序。 The user enters a value out of 100 and the program tells the user if their guess is too high or low. 用户输入的值必须为100,程序会告诉用户他们的猜测是太高还是太低。 I want to make it so the program lets the user know that they've already entered that current number in previously. 我要这样做,以便程序使用户知道他们以前已经输入了当前号码。 How would I implement a loop into my program that would take the users guess and compare it to the array list to look for duplicate values? 如何在程序中实现一个循环,使用户猜测并与数组列表进行比较以查找重复值?

#include <ctime>
#include <iostream>
#include <iomanip>
using namespace std;
#include <cstdlib>

int main() 
{
  srand(time(0));
  const int SIZE = 100; //array
  int number[SIZE];
  int i;
  int numb = rand() % 100; //rng
  cout <<"Hint: "<< numb << endl;
  cout << " " << endl;
  cout << "I'm thinking of a number between 1 and 100. Guess what it is: ";
  for (i = 0; i < SIZE; i++)
  {
    cin >> number[i];
      if (number[i] == numb)  
      {
        cout << "Correct! It's " << numb << endl; //if user guesses correct
        break;
      }
      else if (number[i] < numb) //if user guesses too low
      {
        cout << "That's too low! guess again: " ;
      }
      else if (number[i] > numb) //if user guesses too high
      {
        cout <<  "That's too high! guess again: " ;
      }           
  }
}

Create a vector for already typed values: 为已经输入的值创建一个向量:

vector <int> atyped;

Create a function to check and return true or false: 创建一个函数来检查并返回true或false:

int check(int entered_value, vector <int> atyped) {
ret=0;
  for (int i=0;i<atyped.size();i++){
    if (enterd_value==atyped[i])
     ret=1;
  }
return ret;
}

Then all you have to do is: 然后,您要做的就是:

if (check(number[i])!=0)
cout << "Sorry, you already tried that one!" <<endl;

Hope this can at least give you an idea as to how to solve your problem ;) 希望这至少可以给您一个解决问题的想法;)

Use std::find 使用std::find

for (i = 0; i < SIZE; i++)
{
  cin >> number[i];
  if  (number[i] == numb)
  {
    cout << "Correct! It's " << numb << endl; //if user guesses correct
    break;
  }
  else if (std::find(number, number + i, number[i]) != number + i) 
  {
    cout <<  "You already guessed that! guess again: " ;
  }
  else if  ... // existing higher or lower
}

The range of pointers [number, number + i) is all the previous guesses. 指针的范围[number, number + i)是先前所有的猜测。 find returns the first matching pointer, or the end ( number + i ) if there is no match. find返回第一个匹配的指针,如果没有匹配,则返回结尾( number + i )。

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

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