c++ - How to move cursor to end of text output after cin.clear() and cin.ignore()?
问题描述
After clearing invalid input with std::cin.clear() and std::cin.ignore(), the cursor moves to the beginning of the next line printed by std::cout. I experimented with including an extra std::endl in various positions, to no avail.
Is there any way to force the cursor to the end of the line?
Prompt
do {
std::cout << "Enter a number: ";
if(!(std::cin >> number)) {
std::cout << "Not a number. Try again..."<< std::endl;
std::cin.clear();
std::cin.ignore(10000, '\n');
}
} while (number != -1);
Output
Enter a number: |
Invalid input. Try again...
|Enter a number:
- '|' represents the cursor position
解决方案
std::cout isn't always what you think it is. It's not "the output to the terminal" - it could be output to a file, or even printer. Moving the cursor around on a printer wouldn't do what you might want it to do.
As such, you could TRY printing backspace characters (\b) and see what happens, but better yet would be to obtain a terminal library - like ncurses; which will give you far better control of the cursor.
推荐阅读
- python - selenium WebDriverExeption 状态码是什么意思?
- python - Paramiko 忽略 python 脚本异常
- ios-simulator - 外部 SSD 中的 iOS 模拟器显示黑屏
- python - 需要帮助来检查 sin 结果不匹配,在 python 中使用 taylor 系列
- angular - NativeScript - WebView 上的后退按钮
- r - 在旋转的三角矩阵旁边添加彩条
- python - 错误:找不到满足 matplotlib 要求的版本(来自版本:无) 错误:找不到 mathplotlib 的匹配分布
- akka.net - 如何覆盖自定义日志的 PersistenceTestKit 配置?
- package.json - 如何解决:./src/reportWebVitals.js 中的错误语法错误:'import' 和 'export' 可能只出现在顶层
- neovim - BufWritePost 链接命令