views:

128

answers:

4
+6  A: 

The correct code should look like:

#include <iostream>
#include <string> 
using namespace std;

struct dude {
  string name;
  int age;
};

int main() { 

  struct dude about;
  about.name = "jason";
  about.age = 4000;

  cout << about.name << " " << about.age << endl;
  return 0;
}

EDIT: Added the necessary includes so that it compiles. Also, as a best practise, moved type definition outside of function.

Joy Dutta
Yours is much better than mine. +1
Martin York
@Martin: not really sure, your was complicate but at least pointed the good way to do it!
RageZ
+2  A: 

In addition to Joy's answer, you need to use the std namespace:

std::cout << about.name << " " << about.age << endl;

Also, what are you trying to achieve? Maybe it's better if dude were a class?

Jacob
The `class` and `struct` class-keys are identical in C++, except the first defaults to private, and the second to public, for bases and members.
Roger Pate
+6  A: 
#include <iostream>
#include <string>

struct Dude {
  std::string name;
  int age;
};

int main() {
  using namespace std;
  Dude jason = { "Jason", 4000 };
  cout << jason.name << " is " << jason.age << " years old.\n";
  return 0;
}

In no particular order:

  • define your types outside of functions
  • name types consistently ("Dude" here)
  • provide values when initializing objects
    • I've used aggregate initialization here, you will use slightly different syntax when you write a constructor (ctor)
  • the C++ stdlib is almost exclusively in the std namespace
    • you can place using namespace std; at function scope, if you like, instead of typing std:: within that function body
  • the C++ stdlib string type is from the <string> header
  • main returns int

Fixing these problems isn't really debugging, you just need to learn the correct syntax. Make sure you have a good book (e.g. Accelerated C++ by Koenig and Moo) and a good teacher doesn't hurt.

Roger Pate
+1 struct About is better than struct dude from semantic point of view.
Joy Dutta
Joy: I agree, but I thought it'd cause him more confusion, so I renamed.
Roger Pate
thank you r. pate for your help:) do you know of anybody who teaches c++? i would rather home-based rather than in school or uni
baeltazor
Roger Pate
+2  A: 

You mean how to get it to compile!

You forgot to put

using namespace std;

I think you should pick up a good C++ book, spend some time reading it and come to SO like site afterwards. Just a sincere advise, no offense.

Murali
thank you @wizard@, your so nice
baeltazor