2

so I have a text-based Adventure Game and its running smoothly but one of my "beta testers" noticed that he could select multiple numbers in the first cin spot and it would use those values for the rest of the game. Can I manually put a block on how many characters the user has to type? Here's my program

#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <cstdlib>

char Choice;
char my_name;

using namespace std;

int main()
{
    printf("You come out of darkness.\n");
    printf("Confused and tired, you walk to an abandoned house.\n");
    printf("You walk to the door.\n");
    printf("What do you do?\n");
    printf("1. Walk Away.\n");
    printf("2. Jump.\n");
    printf("3. Open Door.\n");
    printf(" \n");
    cin >> Choice;
    printf(" \n");

    if(Choice == '1')
    {
        printf("The House seems too important to ignore.\n");
        printf("What do you do?\n");
        printf("1. Jump.\n");
        printf("2. Open Door.\n");
        printf(" \n");
        cin >> Choice;
        printf(" \n");

And so on, you get the gist of it

crashmstr
  • 28,043
  • 9
  • 61
  • 79

2 Answers2

3

This is largely platform dependent and there is no easy catch-all solution, but a working solution is to use std::getline to read one line at a time and either ignore everything but the first character or complain if more than one was entered.

string line; // Create a string to hold user input
getline(cin,line); // Read a single line from standard input
while(line.size() != 1)
{
    cout<<"Please enter one single character!"<<endl;
    getline(cin, line); // let the user try again.
}
Choice = line[0]; // get the first and only character of the input.

Thus will prompt the user to enter a single character if they enter more or less (less being an empty string).

Agentlien
  • 4,996
  • 1
  • 16
  • 27
2

If you want the player to be able to press keys like 1, 2 or 3 without having to press enter, you're quickly getting into platform-specific code. On Windows, the old-school (and by old-school, I mean "dating back to the DOS days of the 80s") console way is with the conio routines.

There's nothing within standard C++ which defines that sort of interface, though.

Another approach is to use getline to get an entire line's worth of text every time, and then discard everything past the first character. That would keep you within plain C++, and fix your immediate issue.

Joe Z
  • 17,413
  • 3
  • 28
  • 39
  • Thanks! But where would the getline go? under the cin operator? – TheAwesomElf Nov 27 '13 at 14:52
  • Here's the raw docs for `getline`: http://en.cppreference.com/w/cpp/string/basic_string/getline What you need to do is declare a `string` to capture the input into, and then look at the first bit of the string to determine what the player chose. You'd do best factoring that out into a dedicated function. – Joe Z Nov 27 '13 at 14:58