while 循环之外的 else 语句
else statement outside of a while loop
我正在尝试在读取数据的while循环中安装if和else语句。
以下是简化的代码:
char customColor;
cin >> customColor;
while (!ws(file).eof())
{
file >> color;
if (customColor == color)
{
//////////////////
}
else
cout << "invalid color" << endl;
}
问题是,每当我输入的内容与文件中的内容不匹配时,控制台都会写入"无效颜色",而我试图做的是仅在文本文件中没有结果与我输入的颜色匹配时才写入"无效颜色"。
我想知道是否有任何方法可以将 else 语句放在 while 循环之外。
您可以使用 if else 语句来设置一个布尔值,以检查文本文件中是否没有与您输入的颜色匹配的结果。
char customColor;
cin >> customColor;
bool check = false;
while (!ws(file).eof())
{
file >> color;
if (customColor == color)
{
check = true;
}
}
if (!check)
{
cout << "invalid color" << endl;
}
如果有任何方法可以将 else 语句放在 while 循环之外。
你不能直接这样做,但你可以创建一个标志变量并为其做一些簿记。
char customColor;
cin >> customColor;
bool matched = false;
while (!ws(file).eof())
{
file >> color;
if (customColor == color)
{
//////////////////
matched = true;
}
}
if (!matched) {
cout << "invalid color" << endl;
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 如果 else 语句不断循环
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 如果 else 语句使用大写和小写字母
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 嵌套的 else 语句 c++
- 为什么切换 if else 语句的顺序会导致错误?
- 如何使用 if else 语句
- if/else 语句输出由于加号或减号而未显示正确的消息
- if-else 语句仅按特定顺序工作,我不知道为什么
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如何在C++中为 if 和 else 语句定义新行为
- 如何在 if-else 语句中使用 C++20 的可能/不太可能属性
- While循环和if/else语句工作不正常