TheAwesomElf
TheAwesomElf

Reputation: 51

How can I get the getline operator to work?

So in a previous question, I was told to add getline to make it so users can only use one character for a cin operator. Here 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");
    string line;
    getline(cin, line);
    while(line.size() != 1)
    {
        printf(" \n");
        cout<<"Please enter one single number!\n";
        printf(" \n");
        getline(cin,line);
    }    
    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");
    }
}

But when I run the program it goes through and i type 12 and will say "Please enter one single number!", but then if I put just 1 then nothing happens.

What is wrong with the program?

Upvotes: 1

Views: 87

Answers (2)

Monkeybutt
Monkeybutt

Reputation: 15

Angew is right, but you don't have anything utilizing the line in your while loop either. Also, if the user is just inputting numbers, you don't need getline. You can just use the cin >> choice;

Upvotes: 1

After getline() runs, the 1 you entered has been read from cin and is stored in line. You'll have to extract it from there. Replace this:

cin >> Choice;

with this:

Choice = line[0];

This is all rather basic C++; I suggest you pick up a good book.

Upvotes: 4

Related Questions