Search code examples
c++stringpass-by-reference

Trying to pass user input into string (C++)


I am currently working on string and working on this simple example. I am trying to pass the "birthdate" user input into my logSuccess string when it is ptinted. Done a lot of googling but haven't found solution yet. Any tips?

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

std::string birthdate;

void printString(const std::string& string)
{
   std::cout << string << std::endl;
}

void getBirthdate()
{
   std::cout<<"When is your birthday? "<<std::endl;
   cin>>birthdate;
}

int main()
{
std::string name = std::string("Dame") + " hello!";
std::string logSuccess = std::string("Thank you! We will send you a postcard on ") + birthdate;


printString(name);
getBirthdate();
printString(logSuccess);


std::cin.get();
}

Solution

  • Your error is here:

    std::string logSuccess = std::string("Thank you! We will send you a postcard on ") + birthdate;
    printString(name);
    getBirthdate();
    printString(logSuccess);
    

    It should be:

    string name = string("Dame") + " hello!";
    string logSuccess = "Thank you! We will send you a postcard on " ;
    
    printString(name);
    getBirthdate();
    logSuccess += birthdate;
    printString(logSuccess);