Hello i have put this into devshed

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

int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
cout << "How old are you? ";
getline (cin, mystr);
cout << "I am" << mystr << " too!\n";
return 0;
}

I run it
It asks me my name, i put it in and press enter
it then asks me how old i am i put my age and press enter and the program closes!
Can somebody tell me why this is happening?

The problem is common in mixing cin and getlines. I won't go into the explanation (it's all over the place), but I'll tell you the solution. cin.ignore() before getline().

Also please use code tags when posting code. This is an easy code-sample to read because it's so small. But it becomes impossible to coherently analyse larger code without them.

i have another problem now
when i put that code before getline i compile it and it says

13 C:\Dev-Cpp\main.cpp expected `;' before "getline"

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

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr);
  cout << "Hello " << mystr << ".\n";
  cout << "How old are you? ";
  cin.ignore()[B];[/B]
  getline (cin, mystr);
  cout << "I am" << mystr << " too!\n";
  return 0;
}

still terminating :(

Sorry. I'm having fierce problems reading people's threads today!

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

int main ()
{
  string mystr;
  cout << "What's your name? ";
  getline (cin, mystr);
  cout << "Hello " << mystr << ".\n";

  cout << "How old are you? ";
  getline (cin, mystr);
  cout << "I am " << mystr << " too!\n";

  cin.ignore();
  cin.get();

  return 0;
}

You can put in both your details? Your age and name. It's just closing, right?

yes
i put in my name
worked
put in my age
cuts out
works fine now though thanks

clear mystr before the second getline() ????????
mystr = "";

its okay it works now

Nah. The problem was the program was terminating before he could see the output, so the 'pausing' code sorted it out.

Nah. The problem was the program was terminating before he could see the output, so the 'pausing' code sorted it out.

AHA! So it's actually an IDE issue where the screen exits upon termination?
I use Codeblocks . You have to manually exit.
This would not be an issue even if he used Vim and a "terminal' GUI in Linux.
I wonder why the IDE folks don't correct that?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.