When the input will stop? - c++

Hi guys i have the following question:
string s;
std::cout << "give me a string" << std::endl;
while (std::cin >> s){
std::cout << "give me a string" << std::endl;
}
cin.clear();
if s was an integer then i know that if i typed a char then the while would break. If it was an integer and typed a double the same would happened. But what about strings ?? Somewhere I read that in windows (as I am writting at netbeans in windows) you have to press ctrl+z and then it stops as it is taken as a false string. But when i do this , the process freezes and nothing happens.

You need to send the EOF signal, which in Netbeans is Ctrl + D.
However, hitting Enter twice will result in the condition of your loop to resolve in false, causing the loop to stop. That's excpected: How is "std::cin>>value" evaluated in a while loop?
If that doesn't work, use Ctrl + z and a newline character, which is the EOF signal in Windows, as stated here. Ctrl + D is for Linux though, but it works in your case.
The EOF signal closes the input stream, thus breaking the loop.
Moreover, in Netbeans (if the above doesn't work) it seems that you need to run your application from the command prompt to achieve this. Another attempt would be to "press Ctrl + z after pressing Enter", as stated here.

The loop will stop when the input stream is closed.
If you run the program from a shell, then the input stream may be open indefinitely. Exactly how you would close the stream in a terminal, depends on what terminal you are using.
In UNIX, the stream is closed when you send empty input. ctrl + d is the standard key combination for sending (flushing) the input to the stream (^d is the ASCII control code EOT, end of transmission). Pressing enter also sends the input, but it also inserts the end of line character, so it is not possible to use it to send empty input.
ctrl + z is similar in windows, but it has different behaviour (wikipedia):
The EOT character in Unix is different from the Control-Z in DOS. The DOS Control-Z byte is actually sent and/or placed in files to indicate where the text ends. In contrast the Control-D causes the Unix terminal driver to signal the EOF condition, which is not a character, while the byte has no special meaning if actually read or written from a file or terminal.

Related

C++ getline(cin, buffer) doesn't stop when I press CTRL+Z [duplicate]

This question already has answers here:
C++ Issue with cin and CTRL + Z
(2 answers)
Closed 5 years ago.
I'm writing a CLI application in Windows that accepts a string as an input. I assume the end of the input is when user presses Ctrl+Z (that imitates EOF).
When I enter "qwe" and press Ctrl+Z the getline instead of just assigning the "qwe" to tmp asks me to input one more line for some reason. However, the resulting value in tmp is still "qwe" ignoring the extra line. The code I use is the following:
string tmp;
getline(cin, tmp);
UPD:
As it was said in C++ Issue with cin and CTRL + Z, it's just the usual Windows behavior, where the Ctrl+Z symbol must be at the beginning of the line.
To get the multiline input you should use read by characters until you meet '\n' || EOF.
As explained by OP: This is typical Windows behavior, where the Ctrl+Z symbol must be at the beginning of the line or it will not work as expected.
So if you input "foo", then send the EOF signal by pressing Ctrl+Z and then input "bar", "foo" will be read as expected and then EOF will wait in the input buffer until "bar" is typed too. The program, as is, will stop at EOF and "bar" will be ignored, even though the user typed it.
Read more in C++ Issue with cin and CTRL + Z.

Difference between entering values in cin using spacebar and enter key?

What is the difference between inputting a sequence of values for an array of integers in cin using a SPACE and an ENTER key?
For example -
If I have to input a sequence of numbers in an array and stop receiving the input as soon as 0 is entered by the user in the chain of values. It works correctly if ENTER is pressed on the keyboard to separate each number during input whereas on using SPACE it doesn't stop the input process. Can the below code be modified in some way, so that it works for the SPACE as well?
#include<iostream>
using namespace std;
int main()
{
int arr[10];
int i=-1;
do{
cin>>arr[++i];
}while(arr[i]!=0);
i=-1;
do{
cout<<"\n"<<arr[++i];
}while(arr[i]!=0);
}
"It works correctly if the enter key is pressed to separate each number during input whereas on using the space bar it doesn't stop the input process."
ENTER triggers to read the input stream from an input terminal with cin, while SPACE doesn't.
Usually ENTER from a terminal expands to have the input from the prompt plus a '\n' or '\r' '\n' character sequence sent, and it's considered part of the input.
"Can the below code be modified in some way, so that it works for the space bar as well?"
No, not unless you manage to have a terminal sending input to your program using the SPACE key.
In the end it doesn't really matter for the parsing if you input
1 2 3 4 >ENTER
or
1 2 >ENTER
3 4 >ENTER
std::istream will handle receiving ' ', '\t' or '\n' characters (see std::isspace()) transparently. To send these characters to input is still triggered by the terminal when the ENTER key is pressed.
Space and enter are doing the same thing with respect to cin. It's your mechanism of entry (e.g. your terminal program) that is treating space and enter differently: terminals usually don't pass anything along to your program until you hit enter.
To do what you want, you need to use a library that lets you interact with your terminal. (or maybe your terminal has options you can configure to do this)

How Ctrl Z works actually

Just for curious mind. During problem solving many question says,"Input will be terminated by Ctrl+z". I know its "EOF(End Of File)" But...
while(scanf("%d",&a)==1)
{ cout<<"OK"<<endl;}
while(scanf("%d",&a)!=EOF)
{cout<<"OK"<<endl;}
while(cin>>a)
{cout<<"OK"<<endl;}
Above 3 will be terminated by Ctrl+z.
while(scanf("%d",&a))
{cout<<"OK"<<endl;}
It will give OK by pressing Ctrl+z.
and
while(1){cin>>a;
cout<<"OK"<<endl;}
Its a infinte loop.
I want to know how Ctrl+z works on a program termination. What is the reason behind it. Please answer in details.
Ctrl+z does not terminate your program. It also doesn't pause its execution. It's a 0x1A byte that is interpreted by iostream and stdio methods to be EOF (end-of-file). After that character is read from the console, nothing is read further and the method that is reading it returns. In the case of iostream, std::ios::eof() becomes true.
You would notice in your last case that if you structured it as:
while(cin >> a) { ... }
It would exit like the others.

Line spacing after endl and cout?

I noticed that in the following code:
cout << "Please enter your number: ";
cin >> Number;
cout << "Is this spaced";
The output in the command window for C++ automatically puts "Is this spaced" in the next line. It spaces whatever is after the cin line without needing to use the stream manipulator (why is this called a stream manipulator?) endl. Whereas if I just have the code:
cout << "Please enter your number: ";
cout << "Is this spaced";
It won't automatically space the line with "Is this spaced". Instead both lines are joined up. I am curious to know why this is the case because I always thought that you need endl in order to create a new line of space.
Thanks!
cout << "Please enter your number: ";
cin >> Number;
cout << "Is this spaced";
There's more to this than meets the eye. std::cout and std::cin are - by default - tied streams. That means that std::cout is automatically flushed (i.e. any pending output flushed from any buffers inside your program out to the operating system) whenever std::cin is asked for input. That's why you can be sure to see "Please enter your number: " before the program pauses to wait for you to type. Of course, in most Operating Systems you can start typing before the program's waiting - it will echo it to the terminal and remember it to provide to std::cin later: that's also what happens when you invoke a program with a pipeline such as:
echo "123" | the_program
The input's available when the_program starts running, but sits there for cin >> Number; to attempt parsing. In this case though, there's no keyboard input for the terminal program to echo, and hence the "123\n" sequence isn't echoed to the screen between your two lines of output - without that newline "\n" your output will all appear on one line.
If you want to read from the keyboard without the keyboard input moving the cursor to the next line, you'd be best off using ncurses or some similar library. The libraries can use escape sequences appropriate to your terminal (if available) to reposition the cursor to your liking. It may be practical to code that up yourself if you have a very limited range of terminals to support (e.g. just xterm-compatible ones, VT220, or Windows command shells). It's also generally possible to suppress the printing of keyboard input, but then the user couldn't see themselves type the digits. Another option is to set the terminal to an input mode supporting character-by-character input reading (some terminals default to line-by-line so you can't see characters until return is pressed) - combining that with the suppressed echo above your program can print digits as they're typed, but not print the newline.
Separately, it's good practice to end your program's output with a newline, as some invocation environments won't show the final line otherwise. And, it's somewhat contentious but IMHO best practice not to use std::endl when you don't need to flush the output - just use \n and let the C++ iostream library buffer multiple lines and write them in efficiently sized chunks to the operating system.
Explanation of flushing
Say you have a program like this:
std::string h = "hello ";
std::string w = "world";
std::cout << h;
std::cout << w << '\n';
At some stage, the program needs to tell the Operating System (Linux, Windows etc.) about the text to be printed, letting it send it to a shell/cmd prompt (which might send it on to the screen and put it in buffers for scrollbars etc.), a file or whatever. In the grand scheme of things, it's slow for the program to tell the operating system to do this kind of thing, so the program as a whole will work faster if it remembers "hello ", adds "world" and \n (a newline) to it, then sends "hello world\n" to the operating system all at once. That intra-program storage and concatenation of data is called buffering, and the act of writing data from the buffer to the Operating System is called flushing.
By default cin ends reading stream when it receives a newline which also adds a new line.
When you use cin (std::cin) with the terminal, you often have to press enter to tell the terminal "hey, my input is done."
Enter is also translated as a newline, so it's sticking what is essentially a std::endl because you pressed Enter.
In many cases, you can use the backspace character \b to backtrack the console's current writing. It may work for you to try std::cout << '\b': it happened to backtrack in my terminal (Windows).

istream_iterator ignoring EOF (Ctrl+D) when reading chars

I'm trying to use istream_iterator for reading characters from cin. I've read that pressing Ctrl+D sends an EOF character which ends the input stream. Unfortunately, something is going wrong with it. Here's my code:
#include <iterator>
int main()
{
using namespace std;
istream_iterator<char> it(cin), eos;
while (it != eos) clog << *(it++);
}
I'm running it and typing: as df, then pressing Ctrl+D.
It outputs only asd without the last f and then hangs waiting for input. When I type gh and press Ctrl+D again, it prints the remaining f at last, and the g from next input, but again without the last h. And when I finally press Ctrl+D without typing anything, it prints the remaining h and exits.
I expected it to read asdf and exit, since I already pressed Ctrl+D at the end of this first sequence.
Why is it still waiting for input after getting EOF?
Why it doesn't print the last character read before EOF?
And why it exits only when I press Ctrl+D without typing anything before?
How does this loop need to change to make it behave in the way I expect? (i.e. stop reading immediately after getting Ctrl+D sequence in the input, no matter I typed anything before or not, and reading all characters up to the EOF).
Input iterators require special care. Rewrite your loop this way and the behavior will become similar to any other character input loop:
while (it != eos)
{
clog << *it;
it++;
}
That will take care of "Why it doesn't print the last character"
PS: as for EOF in the middle of the line, it is the POSIX-mandated behavior:
When received, all the bytes waiting to be read are immediately passed to the process without waiting for a newline, and the EOF is discarded. Thus, if there are no bytes waiting (that is, the EOF occurred at the beginning of a line), a byte count of zero shall be returned from the read(), representing an end-of-file indication.
On Unix-like systems, typing Ctrl+D triggers an end-of-file condition only at the beginning of a line (i.e., immediately after typing Enter. To trigger an end-of-file condition in the middle of a line, type Ctrl+D twice.