How should i exit out of a loop just by hitting the enter key: I tried the following code but it is not working!
int main()
{
int n,i,j,no,arr[10];
char c;
scanf("%d",&n);
for(i=0;i<n;i++)
{
j=0;
while(c!='\n')
{
scanf("%d",&arr[j]);
c=getchar();
j++;
}
scanf("%d",&no);
}
return 0;
}
I have to take input as follows:
3//No of inputs
3 4 5//input 1
6
4 3//input 2
5
8//input 3
9
When the program comes out of
while
loop,c
contains'\n'
so next time the program cannot go inside thewhile
loop. You should assign some value toc
other than'\n'
along withj=0
insidefor
loop.change
to
Your best bet is to use
fgets
for line based input and detect if the only thing in the line was the newline character.If not, you can then
sscanf
the line you've entered to get an integer, rather than directlyscanf
ing standard input.A robust line input function can be found in this answer, then you just need to modify your
scanf
to usesscanf
.If you don't want to use that full featured input function, you can use a simpler method such as:
There is a difference between new line feed (\n or 10 decimal Ascii) and carriage return (\r or 13 decimal Ascii). In your code you should try:
You also should note that your variable c was not initialized in the first test, if you don't expected any input beginning with '\n' or '\r', it would be good to attribute some value to it before the first test.