Reputation: 10673
With C++ is it possible to give the user a default value with the Cin statement, then have them backspace what they want to change? For instance: I give the user an option to change a string name, I output the name to the screen: "John Doe" and they can backspace to change the name to "John Smith".
Upvotes: 0
Views: 637
Reputation: 61970
I might be crazy, but here's a plain Windows solution that works on Visual Studio 2012 Update 1. It simulates the characters you want entered, which should keep them in the input buffer until they're ready to be read, and then reads input, waiting for a newline.
#include <iostream>
#include <string>
#include <windows.h>
void InsertDefaultName(const std::string &def) {
HWND hwnd = GetConsoleWindow();
for (char c : def) {
SendMessage(hwnd, WM_CHAR, c, 0);
}
}
int main() {
std::cout << "Enter name: ";
std::string name;
InsertDefaultName("John Doe");
std::getline(std::cin, name);
std::cout << "You entered " << name << '\n';
}
It's worth noting that this might not work completely properly if the user is, say, holding down a key before it gets to the InsertDefaultName()
function call. A more robust library is definitely better, but this is here if it works well enough for you without a whole new library.
Upvotes: 0
Reputation: 249532
For features like this and a lot more, take a look at GNU Readline or one of its workalikes. It's basically a library for applications to support command-line editing with familiar features like up-arrow to repeat previous commands, editing of those previous commands, and yes, you can customize the text presented to the user who can then edit it with the same keystrokes one would use in the shell.
Upvotes: 3