无需换行即可获取输入
我正在编写一个程序,它将对矩阵进行操作。我希望用户能够通过一次一行输入数据来将数据输入到矩阵中。因此,它首先会询问行:1,列:1中的值。用户将输入适当的值,然后按回车键,然后输入行:1,列:2的值。
这是窍门:我希望当用户按 Enter 时控制台不要输入新行。相反,我希望它只是插入一个制表符。这可能吗?
非常感谢。
I'm writing a program which will be doing manipulation of matrices. I want the user to be able to enter data into a matrix by typing it in one row at a time. So it will first ask for the value in row: 1, column: 1. The user will type in the appropriate value, and then press enter, after which he will type in the value for row: 1, column: 2.
This is the trick: I want the console to not enter a new line when the user presses enter. Instead, I want it to simply insert a tab character. Is this possible?
Thanks so much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这是可能的。不过,您需要使用控制台/终端库。 Ncurses for *nix、wincon(Windows API 的一部分;您只需 #include
windows.h
即可使用它)...有很多选择。实际的算法只是检查作为按键事件发送的字符/使用各种库的 getkey() 等效项,如果按下的键不是 ENTER 但仍会导致字符回显,则将输入的字符输出到控制台到屏幕(即功能键、大写锁定、Shift 等不会导致控制台或终端窗口出现任何回显),然后如果按下的键确实是 ENTER,则输出
\t
。Yes, it's possible. You'll need to use a console/terminal library, though. Ncurses for *nix, wincon (part of the Windows API; you can just #include
windows.h
to use it)... There are a lot of choices out there.The actual algorithm will simply be checking the characters that are sent as key events/using the getkey() equivalents of the various libraries, outputting the inputted characters to the console if the key pressed is not ENTER but would still cause a character to be echoed to the screen (i.e. function keys, caps lock, shift, etc. wouldn't cause any echoing to the console or terminal window) and then outputting
\t
if the key pressed is indeed ENTER.将光标位置设置回上一行。在 Windows 中,您可以使用
SetConsoleCursorPosition()
。Set the cursor position back up to the previous line. In Windows, you can use
SetConsoleCursorPosition()
.这并不完全是你想要的,但你可以通过使用
getline
获取一行中的行输入,然后使用std::stringstream
解析来获得相同的效果出值。It's not exactly what you wanted, but you could get the same effect by using
getline
to obtain the row input all on one line, and then usestd::stringstream
to parse out the values.