循环继续循环(C ++)(While loop carries on forever (C++))

编程入门 行业动态 更新时间:2024-10-16 00:20:46
循环继续循环(C ++)(While loop carries on forever (C++))

我仍然是c ++的新手,只是尝试使用该语言。

我最近创造了一个'tictactoe'游戏。

我创建了这个简单的外观函数来获取用户板位置(从1到9)。 它似乎工作正常,但我发现了一个奇怪的错误,所以称之为;

每当我输入一个12位数或更高的数字时,循环就会继续打印“无效位置!” 然后到下一行'选择你的位置1-9:'。

我正在使用visual studio编写代码。 它是代码的东西还是完美的? 我渴望从中学习。

这是功能:

int getUserPosition() { int position; while (true) { cout << " Choose your position 1-9: " << endl; cin >> position; if (position < 1 or position > 9) { cout << "Invalid position!" << endl; } else if (board[position - 1] == 'X') { cout << "This position has been taken!" << endl; } else { return position; break; } } }

I'm still quite new to c++ and just experimenting with the language.

I have recently created a 'tictactoe' game.

I have created this simple looking function to get the users board position (from 1 to 9). It seems to work fine but I found a weird bug so to call it;

Whenever I enter a 12 digit number or higher the loop just carries on forever printing 'Invalid position!' and on to the next line 'Choose your position 1-9: '.

I am using visual studio to write code. Is it something with the code or is it perfectly fine? I'm eager to find out to learn from it.

Here's the function:

int getUserPosition() { int position; while (true) { cout << " Choose your position 1-9: " << endl; cin >> position; if (position < 1 or position > 9) { cout << "Invalid position!" << endl; } else if (board[position - 1] == 'X') { cout << "This position has been taken!" << endl; } else { return position; break; } } }

最满意答案

我终于明白了这里的实际行为。 这不是调用未定义的行为,而是定义您不想要的行为。

cin >> position;

这试图读取你的12位数字,它不适合int,所以读取失败。 因为格式错误失败,12位数字仍保留在缓冲区中,因此循环中的下一次传递尝试再次读取它。

当您打算读取键盘输入时,请始终使用cin::getline() 。 cin的错误/清除逻辑不是为了重新同步键盘输入,而是为了重新同步从无法读取错误消息的生成器输入的输入。 将来,当您尝试将cin与管道一起使用时,最好的解决方案是检查cin::fail()并保存程序(如果它已设置)。

I finally understand the actual behavior here. This is not invoking undefined behavior but rather defined behavior you don't want.

cin >> position;

This tried to read your 12 digit number, which didn't fit into an int, so the read failed. Because it failed on a format error, the 12 digit number remained in the buffer, so the next pass around the loop tried to read it again.

Always use cin::getline() when you intend to read keyboard input. The error/cleanup logic in cin is not designed to resync keyboard input, but rather to resync input piped from a generator that can't read your error messages. In the future, when you try to use cin with a pipe, the best solution is to check cin::fail() and bail the program if it ever gets set.

更多推荐

本文发布于:2023-08-06 01:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1442462.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:loop   carries

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!