c++ - How to make void not return when answer == true
问题描述
I made this program and when I type "yes" it should end my program instead it's waiting for me to say something more and then it comes with my void nottrue(); what should I do to avoid this? Here's my code
#include <iostream>
using namespace std;
void CharacterWorld();
void nottrue();
int main()
{
CharacterWorld();
nottrue();
return 0;
}
void CharacterWorld()
{
string CharacterName;
int CharacterAge;
string yesorno;
cout << " Hi, welcome to the Vanish World! " << endl;
cout << " What's your name champion? " << endl;
cin >> CharacterName;
cout << " ...And what's your age? " << endl;
cin >> CharacterAge;
cout << " ... So your name is " << CharacterName << " and your age is " << CharacterAge << " Is that right?" << endl;
cin >> yesorno;
if (yesorno == "yes")
{
cout << " Okey! so let's start your journey champion!" << endl;
}
else
{
cout << " SO what's your name then ??" << endl;
return nottrue();
}
}
void nottrue()
{
string CharacterName;
int CharacterAge;
string yesorno;
cin >> CharacterName;
cout << " and what's your age?" << endl;
cin >> CharacterAge;
cout << " ...Okey, already. Your name is " << CharacterName << " and your age is " << CharacterAge << endl;
}
解决方案
虽然return nottrue()
可以工作,但它只是一个函数调用,因为调用者和被调用函数都没有返回值。你不会以任何方式改变流量。您必须将函数返回的结果用于控制流。例如
bool CharacterWorld()
{
//...
if (yesorno == "yes")
{
cout << " Okey! so let's start your journey champion!" << endl;
return true;
}
else
{
cout << " SO what's your name then ??" << endl;
return false;
}
}
int main()
{
if(!CharacterWorld())
nottrue();
return 0;
}
还有预定义的exit()
功能来退出程序。
推荐阅读
- xslt-2.0 - 如何匹配xslt中的非字符串
- google-cloud-firestore - Firestore 功能将整个文档数据保存到 Algolia
- reactjs - 使用 CASL 和 graphql-shield 在 GraphQL 后端上的 RBAC 并与我的 React 前端共享规则
- spring-security - Spring Security SAML2 问题签署 SAMLRequest
- java - 将客户端文件从服务器(部署在计算引擎上的弹簧启动应用程序)上传到谷歌存储桶
- reactjs - 如何在 React Material UI 工具栏中放置徽标
- flutter - Flutter中初始化页面和singleItem = true时如何选择默认项(itemTag)?
- java - 无法编组 EJB 参数?
- javascript - 如何使用 Jquery 或纯 JavaScript 更改 URL 参数名称?
- java - 为接口创建 Bean