Currently started to look at pointers,ive read through a fair few books etc on pointers,none seem to cover an actuall user input for example if a user types in 5 it then displayes the memory address.
Most of the pages ive read are values pre set,anyone know of any usfull links in regards to users input?
what ever numbe the user inputs,i have to answer this:
Write a program that asks the user to store a numerical value. Add a simple menu that allows them to either recall the value they just entered or its address in the system memory. You must use the pointer and address operator in your solution!
#include <iostream>
usingnamespace std;
int main()
{
int number;
int *ptr = &number;
cout<<" Please enter a number \n";
cin>>number;
cout << "Your number address is: " << &number;
cin.get();
cin.get();
return 0;
}
i have this so far,i need to figure how to put this in a menu and how to just recal the original number input,would i be on the right track using something like
the above compiles but no matter what number is inputed it allways outputs the same address?
Don't worry. That's what it's supposed to do. You want the user to be able to enter a choice in your menu only once? Or to be able to choose indefinitely until he explicitly decides to stop? Both require an if/switch statement and the latter also requires a loop.
#include <iostream>
usingnamespace std;
int main()
{
int number[0];
int choice;
cout<<" Please enter a number \n";
cin>>number[0];
cout<<" Do you want to recal your number or see the numbers address? \n";
cout<<" Press 1: Recal Number or 2: Display Numbers Address \n";
cin>>choice;
if (choice == 1)
{
cout<<"The number you enterd was: " <<number[0]<<endl;
}
elseif (choice == 2)
{
cout << "Your number address is: " << &number[0];
}
cin.get();
cin.get();
return 0;
}
the above compiles,im not sure if ive answerd the question in regards to the address though?
It indeed compiles (although I'm not sure if it should) and the output is right. Remove '[0]'s at the end of your 'number' variable and it should be just fine!
As for always returning the same address, that would be because you're always storing the integer in the same place. There are no massive changes in memory allocation between your runnings of the program. m4ster r0shi hinted at this, I believe.
To demonstrate this, try initializing something before your number variable. The address will change.