|
-
October 6th, 2005, 05:03 PM
#1
beginner, need help with homework...
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.
Code:
#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;
}
Last edited by af1892; October 6th, 2005 at 05:08 PM.
-
October 6th, 2005, 05:14 PM
#2
Re: beginner, need help with homework...
You have an extra cin.get in your main()
-
October 6th, 2005, 05:37 PM
#3
Re: beginner, need help...
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);"?
-
October 6th, 2005, 06:07 PM
#4
Re: beginner, need help...
 Originally Posted by af1892
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...
"Programs must be written for people to read, and only incidentally for machines to execute."
-
October 6th, 2005, 06:15 PM
#5
Re: beginner, need help...
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)
Last edited by wschweit; October 6th, 2005 at 06:18 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|