PDA

View Full Version : Super basic C++ question



Arowa704
11-20-2003, 12:44 PM
#include <iostream.h>

void main(){
int x =999;
cin>>x;
cout<<x;
}

in this book, I'm reading, it says if i eneter a non numeric number like a, it will not read the input and print out what it has, in this case, it is 999. But on my system, it prints out 0. Can someone explain?
Thanks

Paul Komski
11-21-2003, 03:49 PM
Not sure because I've never used C as such but you could try declaring the variable first - and then give it a value.

void main()
{
int x;
x = 999;
cout << x;
}

or if you are inputting as a separate process

void main()
{
int x;
cout << "Enter an integer such as 999\n";
cin >> x;
cout << "You entered " << x << " didnt you!";
}

yawningdog
11-28-2003, 10:12 PM
Weird, the preprocessor directive isn't showing the included library. Well, anyway...

I may be able to help you, but you must fix your code first.I don't think a modern compiler will allow


void main()

I'm pretty sure gcc doesn't, and its a bad idea anyway. Main should always return something, usually an int.

I'm quite sure that...

cout<
won't compile. The operator << has to be complete. Eliminating all your errors in syntax, I think your code should look like this...


#include <iostream> // or <iostream.h> depending on your compiler
using namespace std;

int x;
int main()
{
x = 999;
cout << "enter x: ";
cin >> x;
cout << x;
return 0;
}

Now then, this exact code typed into vim and compiled with gcc gives an output of 999, which is exactly as I assigned to x in line 7. I input an "a" but it was not assigned to x, I guess because x is an int, not a char.