0

This is a basic c++ console application that I am working on, just to test things out before o do something a little bit more advanced. I would like to know how I would find out if the user input is part of my String array with an if statement here is the code so far...

#include <iostream>
#include <string>

using namespace std;

int main(){

    string array[] = {"1","2","3"};

    for(;;){
        cout << "Enter a random number";
        int randNum = 0;
        cin >> randNum;
        if(/* randNum is part of the array */)
        {
            //do something
        }
        else{
            //do something
        }

    }
    return 0;

}
1
  • You have a string array, but enter an integer value. You should either make an int array or enter a string value. Commented Oct 15, 2012 at 23:37

2 Answers 2

1

First off, you clearly want to check your input after reading:

if (cin >> randNum) {
     ...
}

Next, I think you would want to align the types, i.e., if you read an int you probably want to have your array also to contain ints:

int array[] = { 1, 2, 3 };

If these are given you can just check like so:

if (std::end(array) != std::find(std::begin(array), std::end(array), randNum)){
    ...
}

(if you don't use C++ 2011, you need some other way to get the begin and end iterator your array but there are plenty ways, including defining templates begin() and end() as needed).

If you really want to check the int against an array of std::strings, you'd need a predicate which checks the int against a std::string.

Sign up to request clarification or add additional context in comments.

2 Comments

so would this allow me to have it put the index number into a variable if it did find it was in the array?
Well, you can std::find() the position, storing it in a suitable iterator, check whether it isn't the end iterator, and if so, you can get the index as it - std::begin(array). You can get the index immediately but you might get an out of range index if the value isn't found. Of course, it may be useful to search not quite to the end and have a sentinel value in the last element.
0

You can utilize std::find for this, however, you'll need to convert randNum to a string first -

std::stringstream ss;
ss << randNum;
std::string to_check = ss.str();

if(std::find(array, array + 3, to_check) != (array + 3)) {
//Logic
} else {
//
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.