【问题标题】:Trying to pass user input into string (C++)尝试将用户输入传递给字符串(C++)
【发布时间】:2020-03-15 09:38:04
【问题描述】:

我目前正在研究字符串并研究这个简单的示例。我正在尝试将 "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();
}

【问题讨论】:

  • 想想你做事的顺序!您没有循环,因此main 函数中的代码将严格按照自上而下的方向执行。

标签: c++ string pass-by-reference


【解决方案1】:

你的错误在这里:

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

【讨论】:

  • 明白了。进行了调整,效果很好
【解决方案2】:

在您创建消息并将其分配给 logSuccess 变量时,birthdate 变量为空。您希望在获得用户输入后使用数据填充 logSuccess。

【讨论】:

  • 哦,好吧,我只需要在声明 getBirtdate 函数后放入 logSuccess 变量/消息,然后打印字符串
  • 没错。您仍应在函数开头声明变量,因为这是一种很好的编程习惯,但在输入后将出生日期附加到 logSuccess。
猜你喜欢
  • 2021-08-26
  • 1970-01-01
  • 2021-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-26
相关资源
最近更新 更多