简体   繁体   English

while循环外的else语句

[英]else statement outside of a while loop

I'm trying to fit a if and an else statement inside a while loop that's reading data. 我正在尝试在读取数据的while循环中放入ifelse语句。

Here's the simplified code: 这是简化的代码:

char customColor;
cin >> customColor;   
while (!ws(file).eof())
{
 file >> color;
    if (customColor == color)
    {
    //////////////////
    }
    else
        cout << "invalid color" << endl;
}

The thing is that the console writes "invalid color" whenever what I've entered doesn't match what's in the file and what I'm trying to do is to write "invalid color" only when no results in the text file match the color that I've input. 事实是,只要我输入的内容与文件中的内容不匹配,控制台就会写入“无效的颜色”,而我试图做的就是仅在文本文件中没有结果与之匹配时才写入“无效的颜色”。我输入的颜色。

I was wondering if there was any way to put the else statement outside of the while loop. 我想知道是否有任何方法可以将else语句放在while循环之外。

You could probably use the if else statement to set a bool to check whether no results in the text file match the color that you have input. 您可能可以使用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;
}

if there was any way to put the else statement outside of the while loop. 是否可以将else语句放入while循环之外。

You can't do that directly, but you could make a flag variable and do some bookkeeping for it. 您不能直接执行此操作,但是可以使一个flag变量并为其进行一些记帐。

char customColor;
cin >> customColor;   
bool matched = false;
while (!ws(file).eof())
{
  file >> color;
  if (customColor == color)
  {
    //////////////////
    matched = true;
  }
}

if (!matched) {
  cout << "invalid color" << endl;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM