2

I just want to take space as an empty place as I am coding an 8-piece puzzle problem. However ‘[space]’ is not being accepted.

Here’s the sample function.

void puzzle_8::initial_string_setup()
{
    int i=0;
    string initial="abcdefghi";
    string allowed=" 12345678";
    char to_check;
    bool check=false;
    while(i!=9)
    {
        cout<<"\n\n\t\t"<<initial[0]<<"  |  "<<initial[1]<<"  |  "<<initial[2]<<endl<<"\t\t---+-----+---"<<endl<<"\t\t"<<initial[3]<<"  |  "<<initial[4]<<"  |  "<<initial[5]<<endl<<"\t\t---+-----+---"<<endl<<"\t\t"<<initial[6]<<"  |  "<<initial[7]<<"  |  "<<initial[8]<<endl;
        cout<<"Enter input for place "<<initial[i]<<": ";
        cin>>to_check;
        check=false;
        for(int j=0;j<9;j++)
        {
            if (to_check==allowed[j])
            {
                check=true;
                break;
            }
        }
        if(check==true)
        {
            initial[i]=to_check;
            i++;
        }
        else
        {
            cout<<"\n\nInvalid entry\n\n";
        }
    }
}

Also, how can I stop user from entering double digits?

EDIT:

Changing cin>>to_check to to_check=getchar() lets me take space as an input and solves my query.

vhmvd
  • 192
  • 3
  • 15
  • Does this answer your question? [std::cin input with spaces?](https://stackoverflow.com/questions/5838711/stdcin-input-with-spaces) – openingnow Dec 14 '19 at 15:53
  • `how can I stop user from entering double digits?` I don't understand that, a digit is a character `0`, `1`, ....`9`. What is a "double digit"? You mean inputting a digit followed by another digit? Just remember that the lest character entered was a digit, read next character, and check. – KamilCuk Dec 14 '19 at 15:54
  • 1
    @KamilCuk By double digits, I meant that if user enters lets say 23, it takes it as double input and fills two places. However, I figured that can be avoided by adding an `if` condition in my `for` loop to check if the entry is `>10`. – vhmvd Dec 14 '19 at 16:07
  • 1
    It's almost always bettet to use `std::getline` and then you can validate the input on a line-by-line basis. It will include spaces and you can easily check the lenght of the input to make sure it's only one character. `std::stoi` will let you convert the line to a number. – super Dec 14 '19 at 16:10

2 Answers2

3

The cin or any ios streams can ignore whitespaces (spaces, tabs, newlines) on input depending on the skipws flag.

You can disable ignoring whitespaces with std::noskipws:

cin >> std::noskipws;

Note that then you will have to handle the newlines '\n' and whitespaces in your code in input.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
1

A single space is not recognized as a "full" input by the cin in your code, because it needs to be finished by an enter. You need to replace it by

to_check = getchar();

so, if you type a space it will be saved in your to_check variable