How to read unknown number of inputs?
You need to terminate your input by an End-Of-File-character (i.e. CTRL-Z on Windows, CTRL-D on Mac/Unix), not just by an End-Of-Line (i.e. Enter).
A simple Enter is interpreted as white space, which will be simply ignored by operator>>
when reading into an integral data type.
CTRL-Z / End-Of-File, in contrast, makes any operator>>
fail with an error.
See also this SO answer.
Note: Entering f
will also terminate your loop, since f
is not considered a valid integral number; Hence, std::cin >> value
with value
being of type int
and an input like f
will fail as well. To be more accurate: operator>>
actually returns a reference to the input stream, but if reading in a value fails, failbit
is set on the stream, and then interpreting the stream object in a boolean expression (implicitly calling basic_istream::operator bool()
) returns false
; So maybe the author of the book did not want to explain these details at the respective section in the book :-)
Reading unknown number of lines from console
Try something like this
a_lst = [] # Start with empty list
while True:
a_str = input('Enter item (empty str to exit): ')
if not a_str: # Exit on empty string.
break
a_lst.append(a_str)
print(a_lst)
Reading an unknown number of inputs
You can use an idiomatic std::copy
in C++: (see it work here with virtualized input strings)
std::vector<int> vec;
std::copy (
std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(vec)
);
That way, it will append onto the vector each time an integer is read from the input stream until it fails reading, whether from bad input or EOF.
How to use scanf() input unknown number of objects?
The problem lies with the use of scanf
twice instead of once in the following lines:
while(scanf("%d",&i)!=EOF){
scanf("%d",&i);
printf("%d ",i);
The number you read in the first call to scanf
just gets ignored.
Remove the second scanf
and use just:
while(scanf("%d",&i)!=EOF){
printf("%d ",i);
When you have one variable that you are trying to read into, use of
while(scanf("%d",&i)!=EOF)
is OK. However, when there are more than one variable, it's necessary to use:
while ( scanf("%d %d", &i, &j) == 2 )
since the return value could be 1
if a value was successfully assigned to only i
. It's better to use the the same style of coding even when you are trying to read into one variable. Hence, it's preferable to use:
while ( scanf("%d", &i) == 1 )
scanf unknown number of integers, how to end loop?
while(scanf("%d%c", &numbers, &ch)) { if((ch == '\n') ....
has a couple of problems.
If the line of input has only white-space like
"\n"
or" \n"
,scanf()
does not return until non-white-space is entered as all leading white-spaces are consumed by"%d"
.If space occurs after the
int
, the"\n"
is not detected as in"123 \n"
.Non-white-space after the
int
is discarded as in"123-456\n"
or"123x456\n"
.
how to end loop?
Look for the '\n'
. Do not let "%d"
quietly consume it.
Usually using fgets()
to read a line affords the more robust code, yet sticking with scanf()
the goal is to examine leading white-space for the '\n'
#include <ctype.h>
#include <stdio.h>
// Get one `int`, as able from a partial line.
// Return status:
// 1: Success.
// 0: Unexpected non-numeric character encountered. It remains unread.
// EOF: end of file or input error occurred.
// '\n': End of line.
// Note: no guards against overflow.
int get_int(int *dest) {
int ch;
while (isspace((ch = fgetc(stdin)))) {
if (ch == '\n') return '\n';
}
if (ch == EOF) return EOF;
ungetc(ch, stdin);
int scan_count = scanf("%d", dest);
return scan_count;
}
Test code
int main(void) {
unsigned int_count = 0;
int scan_count;
int value;
while ((scan_count = get_int(&value)) == 1) {
printf("%u: %d\n", ++int_count, value);
}
switch (scan_count) {
case '\n': printf("Normal end of line.\n"); break;
case EOF: printf("Normal EOF.\n"); break;
case 0: printf("Offending character code %d encountered.\n", fgetc(stdin)); break;
}
}
Related Topics
Setting Timeout for C/C++ Function Call
Reading Every Nth Frame from Videocapture in Opencv
Difference Between Const Int*, Const Int * Const, and Int Const *
Why Does an Overridden Function in the Derived Class Hide Other Overloads of the Base Class
What Is a "Translation Unit" in C++
Returning Multiple Values from a C++ Function
Infinite Loop With Cin When Typing String While a Number Is Expected
Generate Random Numbers Uniformly Over an Entire Range
Std::String Formatting Like Sprintf
How to Execute a Functor or a Lambda in a Given Thread in Qt, Gcd-Style
Automatically Add All Files in a Folder to a Target Using Cmake
Countdown Until Matching Digits
Default Constructor With Empty Brackets
What Is "Argument-Dependent Lookup" (Aka Adl, or "Koenig Lookup")
Why Should I Use a Pointer Rather Than the Object Itself
How to Figure Out the Parameter Type and Return Type of a Lambda
Why Should the Implementation and the Declaration of a Template Class Be in the Same Header File