You can use char[]
to read input.
I have modified your program as follows;
int main()
{
int sum=0;
int pos=0;
int neg=0;
double ave=0;
char arr[100] = {'\0',};
std::cout << "Enter an integer, the input ends if it is 0: " ;
gets(arr);
int index = 0;
char ch[1];
bool negativeNumber = false;
while(true)
{
ch[0] = arr[index++];
if(ch[0] == ' ') // Check space and continue;
{
continue;
}
else if(ch[0] == '0' || ch[0] == '\0') // check for 0 or NULL and break;
{
break;
}
if(ch[0] == '-') // Set flag if "-ve"
{
negativeNumber = true;
continue;
}
int digit = atoi(ch);
if(negativeNumber)
{
digit *= -1;
negativeNumber = false;
}
if(digit > 0)
{
pos++;
}
else if(digit < 0)
{
neg++;
}
sum += digit;
}
ave= (double)sum/(pos+neg);
cout <<"The number of positives are " << pos <<endl;
cout <<"The number of negatives are " << neg <<endl;
cout <<"The total is " << sum << endl;
cout <<"The sverage is "<< ave << endl;
return 0;
}
Hope this helps.
2
solved C++ ,Count positive and negative numbers and compute the average of numbers) Write a program that reads an unspecified number of integers