为什么选择0会在循环结束时结束?
有了这段代码,我试图用用户输入的整数值构建一个数组。变量“int selection”是一个int,所以如果输入的值是一个int,while循环应该继续,但值0似乎结束它,我不明白为什么。谢谢你的帮助。为什么选择0会在循环结束时结束?
int main()
{
//data to be entered
int selection;
//array size
int const array_size = 100;
//array
int integers[array_size];
//array index
int index = 0;
//prompt
std::cout << "Enter integer ('x' to quit): " << std::endl;
//get the data
std::cin >> selection;
//while data is int
while (selection)
{
//put it in the array
integers[index] = selection;
//increment index
index += 1;
//get new data point
std::cin >> selection;
}
return 0;
}
false
在C++中被解释为0
。同样,0
被解释为false
。 因此,当selection
是0
,环路有效地变成:
while (false)
{
...
}
不运行。
另一方面,当selection
不是0
时,C++将其视为true
并且循环将运行。
编辑: 如果要循环,而输入是一个整数,尝试
while (std::cin >> selection)
{
...
}
我实际上希望能够取0,我如何才能真正做到这一点。我不需要代码,只是想一想更好的方法 – 2014-09-06 17:25:55
已编辑,请尝试:) – 2014-09-06 17:29:07
谢谢你Ranald。只是为了确保我理解,行(while cin >> selection){}意味着我们可以得到选择是一个int做大括号 – 2014-09-06 17:33:12
由于布尔上下文0
被解释为false
。
此代码不会做什么评论说,它会做:
//while data is int
while (selection)
的数据将永远是一个int
,它不可能存储任何东西在int
变量。
代码实际上做的是在值不为零时循环。
噢,我明白了。那么我应该怎么处理呢?我不需要代码就能更好地思考它。 – 2014-09-06 17:14:54
这是现在的代码是怎么忍受和它的作品。感谢您对所有您的帮助球员
int main()
{
//data to be entered
int selection;
//array size
int const array_size = 100;
//array
int integers[array_size];
//array index
int index = 0;
//prompt
std::cout << "Enter integer ('x' to quit): " << std::endl;
//while data is int
while (std::cin >> selection)
{
//put it in the array
integers[index] = selection;
//increment index
index += 1;
}
return 0;
}
不能编译,因为'std :: din'不存在。 – 2014-09-06 17:49:35
@LightnessRacesinOrbit我认为这是一个错字错误,他的意思是std :: cin – 2014-09-06 18:06:36
是的,我的意思是std :: cin – 2014-09-06 19:40:35
while (selection)
时selection
不再是一个int
不会停止; selection
是总是和int
。
while (selection)
当selection
不等于0
时停止。
您应该测试>>
操作的结果。
'0'等价于'false'。 – 2014-09-06 17:03:39
,因为值“0”可以转换为_bool_“false”。因为值'!= 0'可以转换成_bool_'true'。 – NetVipeC 2014-09-06 17:03:47
将'selection'设置为0会结束你的循环,因为你已经这么说了:'while(selection)'。 – usr2564301 2014-09-06 17:04:01