The starting point here is to consider the input data itself. The logic is built upon the required behaviour given that data.
The input here is from the keyboard, the user will enter zero or more characters and then press the
enter key. That means the input buffer will contain a string of characters something like this:
"abcd\n"
or
"123\n"
or simply
"\n"
for a blank line.
Now we know what the data will look like, we can consider how the program should deal with it. The requirement is to loop repeatedly until the user enters a blank line.
My suggestion was to use the
getline()
. This reads characters from the input buffer until the delimiter (default is newline '\n') is found. The newline itself is read and discarded. If the user had input an empty line, the fail() flag is not set, as this is considered a valid input. So in my code I added a second condition, to test for an empty string.
http://www.cplusplus.com/reference/istream/istream/getline/
Now what about the original code:
|
while (cin.get(x, 10).get())
|
Here, the
cin.get(x, 10)
behaves in a similar manner to getline() with the important difference that it does not remove the delimiter (newline) from the input buffer. Presumably in order to handle that, a
.get()
is tagged on in order to follow the reading of the string with the reading of a single character.
What is the return value in this case? Well, the while() loop is checking the result of this second
get()
. This will return the actual character which was read (presumably the newline '\n') or if for some reason it fails, the returned value is EOF, typically represented as -1. In either case the result is considered
true
since both '\n' and -1 are non-zero values.
http://www.cplusplus.com/reference/istream/istream/get/
http://www.cplusplus.com/reference/cstdio/EOF/
One alternative you could try is instead of:
1 2 3 4 5 6
|
char x[10];
while (cin.get(x, 10).get())
sumt(x);
cin.clear();
|
move the second get() inside the body of the loop, like this:
1 2 3 4 5 6 7 8 9
|
char x[10];
while (cin.get(x, 10))
{
cin.get(); // read and discard the delimiter
sumt(x);
}
cin.clear();
|