声明字符串时遇到问题 P>所以,我今天开始使用C++,想做一个小的基于文本的冒险,但这并不是很好。
这是我的密码:声明字符串时遇到问题 P>所以,我今天开始使用C++,想做一个小的基于文本的冒险,但这并不是很好。,c++,C++,这是我的密码: string answer; string name; string charName; std::cout << "<Ominous voice> Hi there, what's your name?" << std::endl; std::cout << "Enter your name:" << std::endl; getline(cin, name); std::cout << "<Omin
string answer;
string name;
string charName;
std::cout << "<Ominous voice> Hi there, what's your name?" << std::endl;
std::cout << "Enter your name:" << std::endl;
getline(cin, name);
std::cout << "<Ominous voice> " << name << "? That's an... interesting name." << std::endl;
std::cin.ignore();
std::cout << "<Ominous voice> Before we start off... You need to learn the basics, so let's break the fourth wall shall we?" << std::endl;
std::cin.ignore();
std::cout << "<Ominous voice> I'm here to guide you on this wonderfull adventure... for just $ 9.99." << std::endl;
std::cin.ignore();
std::cout << "<Ominous voice> You can name me everything you want, since I'm a fragment of your imagination anyway... So, what about it?" << std::endl;
std::cout << "Enter a name:" << std::endl;
getline(cin, charName);
strcpy (str1,"<");
strcpy (str2,">");
strcat (str1,charName, 1);
strcat (charName,str2, charName.size();
std::cout << charName << " Well then, it seems I'm now called '" << charName << "' not sure if I like that." << std::endl;
std::cin.ignore();
std::cout << "This line does not show up" << std::endl;
字符串应答;
字符串名;
字符串字符名;
std::cout问题在于您尚未声明字符串str1
和str2
您必须在使用字符串str1之前声明它。减量化手段
std::string str1;
在C++中定义为:
str1 = "heureka";
声明总是在定义的前面。
但您可以在一行中同时完成这两项工作:
std::string str1 = "heureka";
或
如果要在字符名称后面添加“”。您可以按如下方式进行操作:
charName = "<" + charName + ">";
charName=”“;
不需要为它创建新字符串。字符串只有一个+运算符,它比strcpy、strcat等更容易使用 您不应该使用strcpy
和strcat
。您希望使用strcpy和strcat的行实现什么?我希望实现在用户输入的开始和结束处放置,例如,如果您放入Jack,它将显示为,并且下一个不会编译:strcat(str1,charName,1)代码>我添加了如何轻松连接字符串的代码。非常感谢,我的代码现在可以工作了,我很高兴我能够在没有strcat的情况下完成它(老实说,这让我很困惑),再次感谢!
std::string str1("heureka");
charName = "<" + charName + ">";