[RESOLVED] Problem after compiling
I'm new to C++ but im really excited about learning this new language. This is my first post on this forum but im really excited to be here. My problem is that as i've been making my first programs i've found that they're crashing for no particular reason! I made some little basic program to see if even that would work but it doesn't! I'm using the Bloodshed Dev C++ compiler. Heres my code.
Code:
#include <iostream>
#include <string>
using namespace std;
int main( void )
{
cout << "Hello, what is your name?";
string name;
cin >> name;
cout << "Hey" << name.c_str();
return 0;
}
Please help, like i said im really new. Any feedback would be most appreciated. It asks me for my name but when i type it in and hit enter it just exits. Sorry if i'm looking really newb right now.
Re: Problem after compiling
The reason that your program just closes after you type in the name is because some IDE's do not automatically pause the program after execution so you can see the results.
There are many different ways to stop the console window from closing so this does not happen.
If you are using Bloodshed DEV-C++ on Windows, you can use this...
Note: some IDE's (like MS Visual Studio.net 2003) will pause the window automatically, so it really depends on your IDE. The system("PAUSE") command is not likely to work with other compilers either, so you may need a different approach.
Alternatively, you can just open up a DOS box manually, CD to your program directory, and manually execute it. If you do it this way, the window will always stay open, even when your program is done executing.
A few other things...
1) Don't use void in a function, especially main(), to indicate no arguments.
It's tacky, and the same meaning can be conveyed by simply using empty paranthesis.
2) No need to use the .c_str() member function of the string class in this case. You can use the << operator with strings directly.
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Hello, what is your name?";
string name;
cin >> name;
cout << "Hey " << name;
system("PAUSE");
return 0;
}
Re: Problem after compiling
Ahh. Thanks alot. It works great now.