2 years ago

#18661

test-img

Good_Username_Taken

Prevent splitting inputs at spaces and automatically using later words for later inputs

I have a Function that outputs a string that it's been given to the console via cout, initializes a new string, writes user input into that string and returns it.

I summarized my problem in this piece of code:

#include <iostream>

std::string GetUserInput(std::string question) {
    std::cout << question;
    std::string inputedData;
    std::cin >> inputedData;
    return inputedData;
}

int main()
{
    std::string userInput1 = GetUserInput("Your first input: ");
    std::string userInput2 = GetUserInput("Your second input: ");
    std::string userInput3 = GetUserInput("Your third input: ");

    std::cout << userInput1 << std::endl;
    std::cout << userInput2 << std::endl;
    std::cout << userInput3 << std::endl;
}

This works, als long as the user doesn't input any spaces. For example if the input is:

Joe
Walther
Alex

Then the Output will be as expected:

Your first input: Joe
Your second input: Walther
Your third input: Alex
Joe
Walther
Alex

But if a user tries to input something that has a space in it, the input will be split at every space character and the words that come after the first will automatically be used as inputs that are requested at later points in time. For that reason, the output looks something like this:

Your first input: Joe Smith
Your second input: Your third input: Walther Jones
Joe
Smith
Walther

What do I need to do in order to write a complete input string with spaces into a variable and then have other inputs right after that are completely independent of the first input and each other?

input

visual-c++

cin

0 Answers

Your Answer

Accepted video resources