# problem with cin in xcode



## tblackma222 (Jul 4, 2006)

Hi. I've just started using Xcode to write c++ program. The program below compiles fine and runs fine, including the "cout" line, until it gets to the "cin >> f" line. I can type in anything and it appears on the screen, but when I hit enter or return, instead of stopping receiving keyboard input, it just goes to the next line. Here's the program:

#include 
using namespace std;

int fact(int x)
{
int n = 1;
for(int i = 1; i <= x; n++)
{
n *= i;
}
return n;
}

int main (int argc, const char * argv[]) 
{
int f;

cout << "Enter the number whose factorial you want: ";
cin >> f;
cout << endl << "The factorial is: " << fact(f) << "." << endl;
return 0;
}

i'm running mac OSX Tiger on a new intel-based macbook pro, and I downloaded Xcode off the apple website, if that's relevant.

Thanks for your help.


----------



## barhar (Jul 4, 2006)

'#include' line is incomplete.
'int fact(int);' is not declared.
'for()' function incorrectly contains 'n++'.
Include 'using namespace std;'; otherwise 'cin', 'cout', and 'endl' would have to be 'std::cin', 'std::cout', and 'std::endl', respectively.

Code rewritten:

#include <iostream>
using namespace std;

long int fact(int);

int main (int argc, char * const argv[]) {
int f;

cout << "Enter the number whose factorial you want: ";
cin >> f;
cout << endl << "The factorial is: " << fact(f) << "." << endl;
return 0;
}

long int fact(int x){
long int n = 1;
for(int i = 1; i <= x; i++){
n *= i;
}
return n;
}

----

fact() could also be written as:

int fact(int x){
 if (x==0) return 1;
 return fact(x-1)*x; // recursive call
}

----

The above code works from 0 to 12, for f in main(); otherwise, a 'long int' overrun occurs, and the resultant value is in error.


----------



## tblackma222 (Jul 6, 2006)

Thank you. That works. I should have known it was human error (more specifically, my error). I'll be more careful with my code in the future.
Thanks again


----------



## HateEternal (Jul 18, 2006)

I'm kind of curious, because I've been starting to look at C++, as to why it was able to compile fine and run with the missing method declaration and the incomplete include statement. Wouldn't cout be an unknown identifier because iostream is never actually included? Does the complier make some assumptions?

Any C++ gurus have a good answer?


----------

