while 循环之外的 else 语句

else statement outside of a while loop

本文关键字:else 语句 循环 while      更新时间:2023-10-16

我正在尝试在读取数据的while循环中安装ifelse语句。

以下是简化的代码:

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