af1892
October 6th, 2005, 05:03 PM
I'm really new to programming. I'm taking a class on C++, and I have had no prior programming experience. If I do this wrong or don't give enough info, please tell me. This is a lab that I am stuck on. It's supposed to take a signed number and the function getInteger() is supposed to read the number character by character until it runs out of numbers. The problem I have is the output always cuts off the first character, whether it's a '-' or a number.
#include <iostream.h>
#include <ctype.h>
#include <string>
using namespace std;
int getInteger(int *);
int main()
{
int x;
cout << "Enter a signed integer: ";
x = cin.get();
cout << endl;
getInteger(&x);
cout << x << endl;
system("PAUSE");
return 0;
}
int getInteger(int *num)
{
char c;
int sign;
int rtrn;
int value = 0;
do
c = cin.get();
while (isspace(c));
if (!isdigit(c) && !cin.eof() && c != '+' && c != '-')
rtrn = 0;
else
{
if (c == '-')
sign = -1;
else
sign = 1;
if (c == '-' || c == '+')
c = cin.get();
while (isdigit(c))
{
value = 10 * value + c - '0';
c = cin.get();
}
value = value * sign;
if (!cin.eof())
cin.putback(c);
rtrn = c;
}
*num = value;
return rtrn;
}
#include <iostream.h>
#include <ctype.h>
#include <string>
using namespace std;
int getInteger(int *);
int main()
{
int x;
cout << "Enter a signed integer: ";
x = cin.get();
cout << endl;
getInteger(&x);
cout << x << endl;
system("PAUSE");
return 0;
}
int getInteger(int *num)
{
char c;
int sign;
int rtrn;
int value = 0;
do
c = cin.get();
while (isspace(c));
if (!isdigit(c) && !cin.eof() && c != '+' && c != '-')
rtrn = 0;
else
{
if (c == '-')
sign = -1;
else
sign = 1;
if (c == '-' || c == '+')
c = cin.get();
while (isdigit(c))
{
value = 10 * value + c - '0';
c = cin.get();
}
value = value * sign;
if (!cin.eof())
cin.putback(c);
rtrn = c;
}
*num = value;
return rtrn;
}