Reputation: 80
The while loop below is supposed to be terminated when there is no input, how can this be achieved?
Also what is the analogous of scanf("%1d" &n)
in C++?
I have tried it using return value of scanf()
and using n==NULL
as condition but both of them lead to an infinite loop.
int n;
int arr[100];
int i=0;
int r = scanf("%1d",&n);
while(r==1)
{
arr[i++]=n;
r = scanf("%1d",&n);
}
Upvotes: 2
Views: 1261
Reputation: 114
If you want to read only one digit number, you can do it with getchar().
#include <stdio.h>
int main(void)
{
int n;
int arr[100];
int i = 0;
int enter = 0;
while(1)
{
n = getchar();
if (n == 10 && enter) break;
if (n == 10)
{
enter = 1;
}
else
{
enter = 0;
n -= 48;
arr[i] = n;
i++;
}
}
return 0;
}
Upvotes: 1
Reputation: 2096
You may try to use scanf
as in the code below.
The code also verifies:
that you don't insert more than the number of elements in the array arr
(ARRDIM
).
that the input of incorrect digits (I.E.: 'a') doesn't create loops.
You have to hit CTRL-D
(Linux/Unix) to stop the data input. (Windows should terminate using CTRL-Z
).
#include <stdio.h>
int main(void)
{
#define ARRDIM 100
int n;
int arr[ARRDIM];
int i=0;
int r=0;
do
{
printf("Insert element %d: ",i+1);
fflush(stdout);
r = scanf("%1d",&n);
if (r>0) {
arr[i++]=n;
} else if (!r) {
printf("Error inserting element: %d ",i+1);
puts("You have to insert only numbers.");
// flushes the wrong input
while ( (r = getchar()) != EOF && r != '\n' );
}
} while(r!=EOF && i<ARRDIM);
puts("Inserted values:");
for(r=0;r<i;r++)
printf("%d\n",arr[r]);
return 0;
}
Note: This code doesn't consider the case where the single input contains more then 1 single numerical digit. If you insert more than 1 digit per input you obtain that the next fields are loaded and if you insert more digits than the max number of digits fitting in the array the overloaded digits remain into the stdin buffer.
Upvotes: 0