Click to See Complete Forum and Search --> : beginner, need help...


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;
}

wschweit
October 6th, 2005, 05:14 PM
You have an extra cin.get in your main()

af1892
October 6th, 2005, 05:37 PM
ok, i have another question, if i take the line "x = cin.get();" out of the code, how do I in itialize 'x' to a value for the line "getInteger(&x);"?

RoboTact
October 6th, 2005, 06:07 PM
ok, i have another question, if i take the line "x = cin.get();" out of the code, how do I in itialize 'x' to a value for the line "getInteger(&x);"?You should've written this code yourself...

wschweit
October 6th, 2005, 06:15 PM
You don't have to since you're only assigning a value later on.
"int x;" declares the variable (which is garbage initially).
&x returns its address (pointer to x) (You don't choose the pointer)