简体   繁体   中英

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();
}

At the time you create the message and assign it to logSuccess variable the birthdate variable is empty. You want to populate the logSuccess with data after you get the input from the user.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM