How can I break a loop when I define an integer array with a number and I want to finish the loop by pressing the ENTER . I test '\\n'
and '\\r'
and '\\0'
and char(13)
and NULL
but didn't work ! for example ( in this code i try to stop the loop with ascii code of ENTER ) :
#include <iostream>
using namespace std;
int main()
{
int n[100];
for (int i = 0; i < 100 && n[i]!=char(13); i++)
{
cin >> n[i];
}
return 0;
}
The behaviour of your code is undefined : you read an element from n
before writing it: int n[100] = {};
is a fix for that.
Your specific problem here is that you need to check the error state of cin
if an int
is not readable from the stream: use something like std::cin.fail()
.
Also, don't hardcode character values (presumably that's what char(13)
is doing?), as then you're not writing portable code. Use '\\r'
&c. instead.
您可以将代码n[i]!=char(13)
更改为n[i-1]!=char(13)
,因为当您检查输入的值时,变量i
已更改为i++
,因此n[i]
的值是未定义的,你将永远得到真实。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.