-1

I know this question has been asked a bit on this site before, but I can't seem to grasp how to get it to work with my particular program.

Essentially, I am creating a little MadLibs type of game, where the player has to enter in certain things in order to fit it into the story. Now, this works perfectly fine if there are no spaces in the user input, HOWEVER the second someone throws in a space, the program can skip an entire question.

Here is my code:

int main(){

    int selection;

    //News Report Variables
    std::string nrfullname;
    std::string nrcrime;
    std::string nradjective;
    std::string nrtown;
    std::string nrpluralnoun;
    std::string nrnounnotplace;
    std::string nrverb;
    std::string nradjective2;
    std::string nrfullname2;
    std::string nrnounnotplace2;

    std::cout << "Welcome to Mad Libs! Please, pick a story!" << std::endl;
    std::cout << "1. News Report" << std::endl;
    std::cin >> selection;

    if (selection == 1) {
        std::cout << "We need a full name of someone." << std::endl;
        std::cin >> nrfullname;
        std::cout << "We need a crime." << std::endl;
        std::cin >> nrcrime;
        std::cout << "We need an adjective." << std::endl;
        std::cin >> nradjective;
        std::cout << "We need a town." << std::endl;
        std::cin >> nrtown;
        std::cout << "We need a plural noun." << std::endl;
        std::cin >> nrpluralnoun;
        std::cout << "We need a noun that is NOT a place." << std::endl;
        std::cin >> nrnounnotplace;
        std::cout << "We need a verb." << std::endl;
        std::cin >> nrverb;
        std::cout << "We need another adjective." << std::endl;
        std::cin >> nradjective2;
        std::cout << "We need a full name of someone else." << std::endl;
        std::cin >> nrfullname2;
        std::cout << "We need another noun that is NOT a place." << std::endl;
        std::cin >> nrnounnotplace2;
    }

As you can probably imagine, most people would opt to put a space where it asks for the full name of somebody (I sure know I would). If they put in that space, it skips the "crime" question and simply moves on to the adjective question.

It would be beneficial if you could show me how to get this to work correctly, as it has been stressing me out a bit, and all of the solutions I've tried have either made the problem worse, or have done nothing to help fix it.

E_net4
  • 27,810
  • 13
  • 101
  • 139
MTS
  • 87
  • 8

2 Answers2

2

Instead of std::cin >> nrfullname, you just have to use std::getline(std::cin, nrfullname [, delim])

std::getline() extracts characters from the input stream and stores the result in nrfullname until the next delimiter. If you don't specify a delimiter, '\n' is used.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

use in std::getline and write: cin.getline(x,sizeof(x))

Elidor
  • 172
  • 1
  • 21