-1

How do I use std::getline to read input with a constant part and variable part.. for example:

constant part: "I_love"

variable part: "cat, dog, donkey, bird....."

And I tried this code by writing: I_love cat

But i realized that "cat" will not be in string Variable, it will be with the constant part and variable part will not have any value I want to have cat in the string Variable

Please can any one tell me what is the problem??

std::string UserInput, Variable;
std::getline(std::cin,UserInput);
if (UserInput == "constant_part" + Variable)
{
    .....
}

Thanks in advance.

WhiZTiM
  • 21,207
  • 4
  • 43
  • 68
Tity
  • 1
  • 1
  • 2
  • Possible duplicate of [Skipping expected characters like scanf() with cin](http://stackoverflow.com/questions/21764826/skipping-expected-characters-like-scanf-with-cin) – WhiZTiM Jun 08 '16 at 00:10

3 Answers3

0

You can't add a std::string to a const char *. You can, however use operator+ to concatenate two strings, so:

if (UserInput == ( std::string("constant_part") + Variable) )
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

getline can be used to read everything (including whitespace) up to either End-Of-File or the next instance of the delimiter character, which you may specify as an argument or leave as the default '\n'. So, you can use it like this:

if (std::getline(std::cin, UserInput, ' ') && UserInput == "I_love" &&
    std::getline(std::cin, Variable))
    std::cout << "the animals loved are: " << Variable << '\n';

If you want to extract the individual animal names one by one:

if (std::getline(std::cin, UserInput, ' ') && UserInput == "I_love")
{
    std::istringstream iss(line);
    while (std::cin >> skipws && std::getline(std::cin, animal, ','))
        std::cout << "someone loves their " << animal << '\n';
}
Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
0

Apart from your obvious problem of using brackets correctly to group expressions, a solution like this:

if (UserInput == ("constant_part" + Variable))

will create a new temporary of std::string and compare.. You can improve this by finding the length of the constant part and then do a substr.

std::string UserInput, Variable;
std::getline(std::cin, UserInput);

//example...
auto LengthOfConstantPart = sizeof("constant part ")/sizeof(char);

//Then you simply do
Variable = UserInput.substr(LengthOfConstantPart);
WhiZTiM
  • 21,207
  • 4
  • 43
  • 68