“并非所有控制路径都返回一个值./&quot“控制可能达到非空隙功能的末端”.验证时循环时
"Not all controlpaths return a value" / "control may reach end of non void function" when validating with while loop?
我正在尝试验证不是整数1、2或3的输入。怎么了?
#include <iostream>
#include <string>
using namespace std;
string decisionThing(int);
int main()
{
int response;
cout << "Enter the section you are in inn";
cin >> response;
do
{
cout << "Are you in section 1, 2, or 3?";
cin >> response;
} while (response != 1 || response != 2 || response != 3);
cout << decisionThing(response) << "n";
}
string decisionThing(int response)
{
string date;
switch (response)
{
case 1:
date = "The test will be held on the 5th.n";
return date;
break;
case 2:
date = "The test will be held on the 6th.n";
return date;
break;
case 3:
date = "The test will be held on the 9th.n";
return date;
break;
}
}
它应该执行do/wher loop是正确的(用户输入了一些输入,例如 155
或 "zebras"
(。
问题是您的while loop 始终返回true。当您使用&&
时,您正在使用||
。任何输入都是not 1
或not 2
或not 3
。
将您的代码更改为此,它将解决问题。
do {
cout << "Are you in section 1, 2, or 3?";
cin >> response;
} while (response != 1 && response != 2 && response != 3);
至于您遇到的错误,可能是您的decisionThing
在现实生活中不会获得一个不是1
,2
或3
的数字,但是编译器不知道。如果该方法获得了不满足任何一种情况的数字,应该会发生什么?它没有定义。因此,我们有一个路径,可以使该代码不返回指定返回字符串的函数中的任何内容。您可以返回空字符串或抛出异常或处理default
案例:
string decisionThing(int response)
{
string date;
switch (response)
{
case 1:
date = "The test will be held on the 5th.n";
return date;
case 2:
date = "The test will be held on the 6th.n";
return date;
case 3:
date = "The test will be held on the 9th.n";
return date;
default:
date = "Wow, this is really unexpected, I guess nothing?n";
return date;
}
}
顺便说一句,当您拥有return
时,您不需要break
s。该函数将立即返回,因此之后的任何内容都无法执行。
相关文章:
- Msgpack中是否具有版本控制功能
- C++ Mac Xcode 错误:控制可能达到非无效功能的末尾
- QCoreApplication事件循环和Windows服务控制处理程序功能
- “并非所有控制路径都返回一个值./&quot“控制可能达到非空隙功能的末端”.验证时循环时
- 警告:控制可能达到非无效功能的终点?返课时
- 递归功能,以打印每个新位置以进行控制
- 控制达到非空隙功能的终点,C++
- FPU控制功能是否与x64_64处理器相关
- 使用C 控制IP相机的PTZ功能
- 此功能是否具有所有控制路径上的明确返回值
- 在API中控制WNDProc功能的问题
- 错误:控制到达非无效功能的末尾
- 控制达到非空功能结束.我该如何解决这个问题
- 使用C++中的设备IO控制功能识别系统保留驱动器
- shared_ptr控制块内部的虚拟功能是什么?
- 在 OpenCV 错误 NULL 指针中使用 Qt 控制面板功能
- 错误:控制到达非无效功能的末尾.找不到修复错误的位置
- 在Linux中寻找流量控制功能(即QOS)库
- SetupDi API:以编程方式控制设备管理器功能
- 检测c++控制台中功能键