Hey - I'm writing a complicated program, and decided to try a few small test programs to make sure what I'm doing is right, and I have run into a problem. I can input a value for a, and then it waits for my input for b. I type "1" and then "enter" and it does not print the value asigned to buy[0] (what I inputed for a)
I'm a n00b, be nice
thx in advance
- Timmah \m/
using namespace std;
int main()
{
int a, b;
int buy[10];
cin >> a;
a = buy[0];
cin >> b;
if (b=='1')
cout << a;
It won't print anything unless you tell it to print. You're not telling it to print. Here's what you're doing:
1 2 3 4 5 6 7
cin >> a; // get a value from the user, put it in 'a'
a = buy[0]; // throw that value out, and reassign 'a' to be whatever buy[0] is
// of course, buy[0] is nothing (uninitialized), so you're basically just destroying 'a' here
// note this doesn't print anything
cin >> b; // get another value from the user, put it in 'b'
cin and cout aren't functions, they are predefined objects of the istream and ostream classes respectively. '::' is the scope operator. std::cin basically means "cin from the namespace std". In your main program you usually write "using namespace std" at the top, which lets the compiler look up symbols in the std namespace even if you don't explicitly address them as part of std with the scope operator. For example:
//namespace
namespace myNamespace
{
constint myLovelyInt = 15;
}
//main version 1
int main(int argc, char** argv)
{
cout<<myLovelyInt //Error, myLovelyInt is not defined in the local namespace
return 0;
}
//main version 2
int main(int argc, char** argv)
{
cout<<myNamespace::myLovelyInt; //Ok, myLovelyInt is in the myNamespace namespace
return 0;
}
//main version 3
usingnamespace myNamespace;
int main(int argc, char** argv)
{
cout<<myLovelyInt; /*Ok, myLovelyInt is not in the local namespace, but it is in myNamespace namespace which we have marked as being used by our program */
return 0;
}
//main version 4
usingnamespace myNamespace
int main(int argc, char** argv)
{
cout<<myLovelyInt; //No myLovelyInt in the local namespace, but in myNamespace
int myLovelyInt = 16;
cout<<myLovelyInt; //This is ok, namespaces prevent name collisions. This will output our local myLovelyInt
cout<<myNamespace::myLovelyInt; //Here we output myNamespace's myLovelyInt again
return 0;
}