Дарья
Дарья

Reputation: 33

checking for input only 0 or 1

the program accepts a string consisting of 0 and 1, how can I limit the input of other numbers? I tried using the while loop:

while(str<0 ||str>1){
   cout << "Enter your string: ";
   cin.getline(str, MAXLINE);
}//  in this case I can only enter 0 and 1

but my string can look like: "11 10 111" and therefore this method is not suitable. How can I make an input check so that different combinations of 0 and 1 are entered, but no other digits are entered?

#define MAXLINE 1000
#include <iostream>
using namespace std;

int main() {

int len = 0;
char str[MAXLINE];

cout << "Enter your string: ";
cin.getline(str, MAXLINE);

    while (str[0] == '\0') {
        cout << "String is empty. Try enter string again: ";
    cout << "Enter your string: ";
        cin.getline(str, MAXLINE);
}


for (int i = 0; str[i] != '\0'; ++i) {
    if (str[i] != ' ' && str[i + 1] != '\0')
        len++;
    else {
        if (str[i + 1] == '\0') {
            len++;
            ++i;
        }
        if (len % 2 == 0) {
            for (int j = i - len; j < i; ++j) {
                cout << str[j];
            }
            cout << "\t";
        }
        len = 0;
    }
}

return 0;
 }

Upvotes: 1

Views: 159

Answers (1)

Vlad Feinstein
Vlad Feinstein

Reputation: 11311

You can check that the std::string contains only 0 and 1 with:

if(str.find_first_not_of("01") != std::string::npos)
  // found invalid character

You could include a space in that if you allow spaces in the input.

See std::string::find_first_not_of

Upvotes: 1

Related Questions