尝试将用户输入传递给字符串 (C++)
Trying to pass user input into string (C++)
我目前正在研究字符串并研究这个简单的例子。我正在尝试将 "birthdate" 用户输入传递到我的 logSuccess 字符串中。做了很多谷歌搜索,但还没有找到解决方案。有什么建议吗?
#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();
}
在您创建消息并将其分配给 logSuccess 变量时,生日变量为空。您想在收到用户的输入后用数据填充 logSuccess。
你的错误在这里:
std::string logSuccess = std::string("Thank you! We will send you a postcard on ") + birthdate;
printString(name);
getBirthdate();
printString(logSuccess);
应该是:
string name = string("Dame") + " hello!";
string logSuccess = "Thank you! We will send you a postcard on " ;
printString(name);
getBirthdate();
logSuccess += birthdate;
printString(logSuccess);
我目前正在研究字符串并研究这个简单的例子。我正在尝试将 "birthdate" 用户输入传递到我的 logSuccess 字符串中。做了很多谷歌搜索,但还没有找到解决方案。有什么建议吗?
#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();
}
在您创建消息并将其分配给 logSuccess 变量时,生日变量为空。您想在收到用户的输入后用数据填充 logSuccess。
你的错误在这里:
std::string logSuccess = std::string("Thank you! We will send you a postcard on ") + birthdate;
printString(name);
getBirthdate();
printString(logSuccess);
应该是:
string name = string("Dame") + " hello!";
string logSuccess = "Thank you! We will send you a postcard on " ;
printString(name);
getBirthdate();
logSuccess += birthdate;
printString(logSuccess);