Originally Posted by
shikhardeep
to whiteflags:-
can you please explain me in detail. i am new to c and c++
Code:
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
struct stu
{
int size;
char name[10];
}*ptr=NULL;
1. ptr=new stu;
2. cin>>ptr->size;
3. cin>>ptr->name;
4. cout<<ptr->size<<ptr->name;
getch();
return 0;
}
1. This assigns a new stu object to ptr. If it does not succeed, new will throw an exception.
2. This changes size if the user enters a valid integer. If the user fails to provide a good integer, then cin will enter a bad state, and size remains unchanged.
3. This line works similarly to 2. The only difference is that the input should be a string that fits in name.
4. You echo the int and name back, but it could be garbage.
Steps two and three and four also depend on the success of step 1. The fact that you're using pointers doesn't matter. As I mentioned, cin operator >> works by reference, and as long as the pointer actually points to a stu object, the code will work.