Default value for input in C++ [duplicate] - c++

My app reads user input using std::cin stream.
In one place I would like to provide default input and let the user to accept it as it is (by pressing enter) or modify it before continuing (by removing old characters with backspace and adding new text).
I'm aware that characters can be placed directly into cin.rdbuf, but that's not exactly what I want to achieve.
I would like to put characters into console window in the place where console's cursor is when waiting for user input and do no read them before user will accept them. User should be also able to remove them and write their own text.
Can something like this be achieve using cin or do I have to simulate this by reading single characters and repainting content of the console?

No, something like that cannot be done with std::cin. Its read buffer is read directly from standard input. Standard input is a "cooked" character stream. All the editing is handled entirely by your operating system's terminal console, and pressing Enter results in your application's std::cin reading the entered text.
The traditional way this is done is to simply indicate the default input value in the prompt itself, and use the default value in the event of empty input, something like:
std::string buffer;
std::cout << "What color is the sky [blue]? ";
std::getline(std::cin, buffer);
if (buffer.size() == 0)
buffer="blue";

Related

Providing default value of cin input

My app reads user input using std::cin stream.
In one place I would like to provide default input and let the user to accept it as it is (by pressing enter) or modify it before continuing (by removing old characters with backspace and adding new text).
I'm aware that characters can be placed directly into cin.rdbuf, but that's not exactly what I want to achieve.
I would like to put characters into console window in the place where console's cursor is when waiting for user input and do no read them before user will accept them. User should be also able to remove them and write their own text.
Can something like this be achieve using cin or do I have to simulate this by reading single characters and repainting content of the console?
No, something like that cannot be done with std::cin. Its read buffer is read directly from standard input. Standard input is a "cooked" character stream. All the editing is handled entirely by your operating system's terminal console, and pressing Enter results in your application's std::cin reading the entered text.
The traditional way this is done is to simply indicate the default input value in the prompt itself, and use the default value in the event of empty input, something like:
std::string buffer;
std::cout << "What color is the sky [blue]? ";
std::getline(std::cin, buffer);
if (buffer.size() == 0)
buffer="blue";

How does getline work with cin?

I feel like there are a lot of similar questions, so I'm really sorry if this is a duplicate. I couldn't find the answer to this specific question, though.
I am confused as to how getline works when cin is passed to it, because my understanding is that it should be calling cin each time it is called. When working with code that was in a book I'm reading though, getline is called several times yet only one input is sent. The cin object is not called from anywhere except for within these getline calls.
What's going on here? When getline is reached does the program simply stop in its tracks and wait for the input stream to pass a value including the desired delimiter? If this is the case, do the subsequent getline calls just not have to wait because the input stream already has data including their respective delimiters? I ran a couple tests that would suggest this could be the case.
Here is the code:
string firstName;
getline(cin,firstName,',');
string lastName;
getline(cin,lastName,',');
string job;
getline(cin,job,'\n');
cout<<firstName<<" "<<lastName<<" is a "<<job<<endl;;
Sorry again if this is a stupid question, but I looked around and genuinely could not find the answer. Thanks in advance for any help that can be provided!
Clarification:
This code outputs "First Last is a Job" for the console input "First,Last,Job\n"
A call to a function using cin is not actually a request for user input (at least not directly). It is a request for characters from the standard input. In normal program operation (where standard input is not being directed from a file or other source) standard input is stored in a buffer. If the standard input buffer is empty, and cin is requesting more characters, then your system will request input from the user via the terminal. (i.e. the keyboard). This input which the terminal requests is generally line oriented. That is, it waits for you to press the Enter key, then sends all the data to be stored in the standard input buffer. If cin gets all the characters it needs before the input buffer is empty, those characters remain until the next request.
So, for example, when you make this call:
getline(cin,firstName,',');
and the input buffer is empty, Let's say the user inputs this:
Benjamin, Lindley, Software DeveloperEnter
First, the following string is stored in the input buffer:
"Benjamin, Lindley, Software Developer\n"
Then getline causes "Benjamin," to be read from the input buffer (but discards the comma).
" Lindley, Software Developer\n"
remains in the buffer for any future operations with cin.
getline does not "call" cin at all. cin is an object. Objects contain data. The data in cin is the information needed by input functions to read the standard input stream. If you wanted to read from a file, for instance, you'd open the file and pass the file object to getline instead.
When getline is called, the program reads whatever is in the input buffer. If the input buffer already contains the delimiter then getline will return right away. Otherwise it will wait.

Is it possible to cout without overwriting current text in the input?

Okay, so let's say I have a program that couts a line while the user may be typing in information.
For this example, let's say we're using the code
cout << "THIS CODE IS BEING COUTED" << endl;
Let's say for our example, the user is in the process of typing up an input and as it stands they have only entered "hello", but has not yet pressed enter.
As it stands, when the line is executed, the user will see
"helloTHIS CODE IS BEING COUTED"
and they will be given a new line to input information.
What I want to do is instead of cout'ing, I would like to get the text in the current input, erase it from the input, cout the line that needs to be cout'ed, and then re-enter the info into the input.
Does this make sense or is this a bunch of jumbled nonsense?
Thanks for reading.
Edit: Clarification: I want it so if I have a string entered into my input and I cout, that the cout will be displayed above my input instead of inserting it past my input. I also want my input to be unaffected so the user can continue typing or delete what was already entered.
If you are getting the input character by character then when you need to output your text you could move the output position to the start of the line by printing carriage return, '\r'. Then your output will overwrite the current input, after which print a line feed and reprint what has been input so far
cout << "\r" << output << "\n" << currentinput;
If the output is shorter than the input then you will only partially overwrite the input, in which case you could pad the output with spaces up to the length of the current input
You may ask user in one, main thread with cin >> data there and read data from stdin in other thread by fread or something like that what works with FILE* handle.
After the data you want was typed by user you may clear screen (for example by clrscr() in conio.h or by any other better way) and cout what you want.

Possible to discard return character when using std::cin >>?

When using the >> operator in c++ to capture user input, is it possible to prevent the console from printing the newline that is generated when the user presses the return key?
You cannot prevent newline character, because when you use cin, you are communicating with system core, which is not under control by users. console will return, when you enter \n or EOF or other exception situation.
So the better way is to use getchar() to capture the '\n', and do not leave it in buffer.
It is possible to prevent this newline behavior by inputting two EOFs instead of Carriage Return from the keyboard. After entering your string at the console prompt, hit
CTRL-D, CTRL-D
Note, this is a platform specific answer. This works on my Mac, but on Windows OS the EOF sequence may be CTRL-Z, RETURN. I would appreciate an answer edit <-- HERE.
Alternately, you can ditch the >> operator and use something like std::getline and specify an exact string termination delimiter. For example:
std::string myString;
std::getline(std::cin, myString, ';');
std::cout << myString;
This will read from standard input to myString, and put the string terminating NULL character where it finds the first semicolon ';'. Then you'll only have to hit CTRL-D (input EOF) once.
You can enter the values or input by pressing space every time. But at the end you must press enter key.
Let's say: you want to enter "5,4,3,2,1"
You can do: 5 [enter] 4 [enter] 3[enter] 2[enter] 1[enter]
Also: 5[space]4[space]3[space]2[space]1[enter]
But if you want to print the output near input, you can simply print the input first and than you can print the what you want.
Example:
Input: 3 Output: input+1
So you will do:
cout<<input;
cout<<" "<<input+1<<endl;
Good luck :)

Getting input without a linebreak

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.
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.
Set the cursor position back up to the previous line. In Windows, you can use SetConsoleCursorPosition().
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 use std::stringstream to parse out the values.
std::string row;
getline(cin,row);
std::stringstream ss(row);
int j=0,i=currentrow; //put this in a loop over your rows
int input; //or float, double, whatever
while(ss >> input)
{
mat[i][j] = input;
j++;
}