Updated code:
Code:
#include <iostream>
using namespace std;
int main()
{
char buf[1000];
int n;
int num_negative = 0;
char* p = buf;
char* pEnd;
cout << "Enter some numbers: ";
cin.get(buf, 1000);
if (atoi(buf) == 0 && *(char*)buf != '0')
{
cout << "Invalid value entered! Try again.\n";
system("PAUSE");
return 1;
}
for (pEnd = p + strlen(buf) + 1; p < pEnd; )
{
n = atoi(p);
if (n < 0) num_negative++;
if (*p == '-') p++;
while (*p >= '0' && *p <= '9') p++;
if (*p != ' ' && *p != 0)
{
cout << "Encountered junk in input. Enter your numbers properly!\n";
system("PAUSE");
return 1;
}
p++;
}
cout << "You entered " << num_negative << " negative number(s)!\n";
system("PAUSE");
return 0;
}
Tested and works.
I can, however, tell you what the code does. First, it asks for some numbers seperated by spaces. It then checks if it is a valid number entered by checking if atoi returns 0 (since it returns 0 on error) and also if the first character in the buffer is the number 0. If atoi returns 0 and the first number entered isn't 0, then an error occoured.
Then it uses pointers to access data. The variable p points to the current position in the buffer where it will read the next character. pEnd is used to point at the end of the buffer. That is the length of the string + 1 (since strings always have a 0 at the end of the string). It checks the current position against the end position and checks if it has passed the end of the used buffer. If it has, then terminate the loop.
Inside the loop, first aquire the number entered. Atoi will check the buffer (starting at the position pointed by p) until it reaches a non-number char and will then stop and returns the number prior to that char.
Then check if it is negative. If it is, the increase the num_negative variable by one.
The app will check if there is a minus sign in the buffer, which would indicate a negative number. If so, increase the read position by one.
Then it checks if the current character in the buffer at the read position is a number (its ASCII value is bigger or equal to 0 and is lower or equal to 9). If it is, then increase read position. If not, then terminate the loop.
Last it will make a sanity check to make sure the next character is a space. If it isn't, then you've entered some junk data.
Lastly, it increases the read position so that it won't read the space next time.
After the loop is done, it checks the number of negative numbers found and prints it to the user.