我正在尝试在读取数据的while循环中放入if和else语句。
这是简化的代码:
char customColor;
cin >> customColor;
while (!ws(file).eof())
{
file >> color;
if (customColor == color)
{
//////////////////
}
else
cout << "invalid color" << endl;
}
事实是,只要我输入的内容与文件中的内容不匹配,控制台就会写入“无效的颜色”,而我试图做的就是仅在文本文件中没有结果与之匹配时才写入“无效的颜色”。我输入的颜色。
我想知道是否有任何方法可以将else语句放在while循环之外。
是否有任何方法可以将else语句放在while循环之外。
您不能直接执行此操作,但可以将一个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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句