Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I'm planning to insert integer's into an array and the loop of inserting must stop when the input was null(meaning by pressing 'enter' without entering any number). But it doesn't work, it gives me a message at the end of compile:

The program '[5068] Insertion_sort.exe' has exited with code 0 (0x0)

C++
int main()
{
	int* arr = new int[];
	int num=0;
	int i=0;
	while ( num = NULL )
	{
		cout<<"please enter element "<<i<<" ::: ";
		cin>>num;
		arr[i]=num;
		i++;
	}
}


Why does it happen?
How can i fix it?

Thanks,
Posted

1 solution

It happens because the main function came to an end without any error being detected: zero is a return code indicating "normal exit".

Why did it exit sooner than you expected? Because NULL is defined as 0. And because "=" is an asignment. And because 0 is "false" as far as C++ is concerned.

So when your code does this:
C#
int num=0;
while ( num = NULL )
{
...
}
It's the equivalent of saying:
C#
int num=0;
while ( false )
{
...
}

I suspect you need to do this:
C#
int num=0;
int i=0;
while ( num == 0 )
{
    cout<<"please enter element "<<i<<" ::: ";
    cin>>num;
    arr[i]=num;
    i++;
}
But that won't work for long either, as you haven't allocates any "real" space to your array!
 
Share this answer
 
v2
Comments
m.r.m.40 26-Jul-14 6:02am    
int arr[10];
int num=0;
int i=0;
while ( num== NULL )
{...}

its not working,
it works when i say :
while ( true ){...}

then how can i give its loop a stop order ?
OriginalGriff 26-Jul-14 6:06am    
Use while(true) and inside the loop check what the user entered: if it's the termination condition, then use break:


while (true)
{
...
if (num == exitValue) break;
}
m.r.m.40 26-Jul-14 6:18am    
It says
"exitValue" is undefined
OriginalGriff 26-Jul-14 6:24am    
:sigh:

Yes, I know - that was example code for you to fill-in-the-blanks...
You might want it to exit when the user enters zero, you might want a negative number.
Since there is no "NULL" key on my keyboard I assume you know the user can't enter it?
m.r.m.40 26-Jul-14 6:30am    
LOL,
I got it, it worked, LOL.
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900