Accept only input chars I want

Hello, I'm fairly new to C++ and I'm constructing a program that defines a FSA, its states, accepting states, alphabet, and state transitions. The program will then go through a loop that will check the state transition and output ...accepted or ...not accepted. I want to be able to check for user input, so if the user inputs the alphabet "a", "b" for the FSA, it will give the message "Invalid Input!" and exit the program. I have this piece of code that checks this, but it only works if I use 1 character, if I use more than one char it won't work. I've been reading online and I've seen a couple of sources saying that if I use getline() that would help but I'm not sure I get how to implement it or if it applies to what I need. Any help is appreciated

1
2
3
4
5
6
7
8
        for (m = 0; m < alphabet[m]; m++) {
            if (input[m] == alphabet[m] || input[m] == alphabet[m+1]) {
                continue;
            }
            else
                cout << "Invalid Input!" << endl;
            exit(0);
        }
With C-style strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstring>

bool check_input(const char *alphabet, const char *input) {
    for (int i = 0; input[i]; ++i)
        if (!std::strchr(alphabet, input[i]))
            return false;
    return true;
}

int main() {
    std::cout << "Alphabet: ";
    char alphabet[100] = "abcd";
    std::cin.getline(alphabet, sizeof alphabet);

    std::cout << "Input: ";
    char input[1000];
    std::cin.getline(input, sizeof input);

    std::cout << check_input(alphabet, input) << '\n';
}

With C++ std::string:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <string>

bool check_input(const std::string& alphabet, const std::string& input) {
    for (char ch: input)
        if (alphabet.find(ch) == std::string::npos)
            return false;
    return true;
}

int main() {
    std::cout << "Alphabet: ";
    std::string alphabet;
    std::getline(std::cin, alphabet);

    std::cout << "Input: ";
    std::string input;
    std::getline(std::cin, input);

    std::cout << check_input(alphabet, input) << '\n';
}

Topic archived. No new replies allowed.