In this section, we’ll address some of the common issues that new programmers seem to run across with fairly high probability. This is not meant to be a comprehensive list of compilation or execution problems, but rather a pragmatic list of solutions to very basic issues. If you have any suggestions for other issues that might be added to this list, post them in the comments section below.
Problem 1: When executing a program from the IDE, the console window blinks and then closes immediately.
Answer 1: Some compilers (eg. Bloodshed’s Dev C++) don’t automatically pause the console screen after the program has finished executing. If this is the case with your compiler, the following two steps will fix your problem:
First, add the following line near the top of your program:
#include <iostream>
Second, add the following code at the end of the main() function (right before the return statement):
cin.clear(); cin.ignore(255, '\n'); cin.get();
This will cause your program to wait for you to press a key before continuing, which will give you time to examine your program’s output before your compiler closes the console window.
Other solutions, such as the commonly suggested system(”pause”) solution may only work on certain operating systems.
Problem 2: When compiling with Microsoft Visual C++, you get the following error: “c:\vcprojects\test.cpp(263) :fatal error C1010: unexpected end of file while looking for precompiled header directive”
Answer 2: This error occurs when the Microsoft Visual C++ compiler is set to use precompiled headers but one of your C++ code files does not include the stdafx header as the first line. To fix this problem, simply locate the file producing the error (in the above error, test.cpp is the culprit), and add the following line at the very top of the file:
#include "stdafx.h"
Alternatively, you can turn off precompiled headers.
Problem 3: When trying to use cin or cout, the compiler says cin or cout is an “undeclared identifier”
Answer 3: First, make sure you have included the following line near the top of your file:
#include <iostream>
In any function where you use use cin or cout, include the following line:
using namespace std;
Problem 4: When trying to use endl to end a printed line, the compiler says end1 is an “undeclared identifier”
Make sure you do not mistake the letter l (lower case L) in endl for the number 1. endl is all letters. I recommend using a font that makes it clear the differences between the letter lower case L, upper case i, and the number 1. Also the letter capital o and the number zero can easily be confused in many fonts. There is a huge list of programming fonts here.
Problem 4: My program compiles but it isn’t working correctly. What do I do?
Answer 4: Debug it! You can find information on how to debug programs in appendix A, specifically sections A.4 and A.5. You will probably find the debugging sections more comprehensible after reading a few more chapters, but I wanted to make you aware of their existence now for future reference.
1.1 — Structure of a program
|
Index
|
0.6 — Compiling your first program
|
1.1 — Structure of a program
Index
0.6 — Compiling your first program
Problem 1: When executing a program from the IDE, the console window blinks and then closes immediately.
The ide I’m using is Visual C .NET 2002. This ide has problem 1.
To fix the problem I include the following command at the end of the main() function before the return statement.
system(”pause”);
[ Unfortunately, this only works on the Windows operating system. The system() function tells the operating system to execute whatever the parameter is -- in this case, a command named "pause". On Windows, this waits for user input. On other operating systems (such as linux), the pause command does something else entirely. However, if you are only programming on Windows and not distributing your source code, you may find this an easier solution while learning. -Alex ]
Another great way to get a program to pause is to require a user input (cin). Using a menu-type interface that requires the user to select an option for “exiting” works well. I’m only a beginner, but for simple calculators that I’ve created, this works well.
In order to get the screen to pause before exiting the program, does the code:
have any advantages over just using
I have so much to learn. :)
Jason, good question. Here’s a simple program that illustrates why
cin >> myVariableis not the best way to pause:#include <iostream> int main() { using namespace std; // Allocate a buffer to hold user input char buf[255] = { 0 }; // We only want one letter cout << "Enter a letter: "; cin >> buf[0]; // Pause and wait for user input char chIgnore; cout << "Pausing" << endl; cin >> chIgnore; return 0; }First,
cin >> chIgnoreignores the enter key if the user does not provide any other input. You can verify this by hitting enter when thecin >> chIgnoreline is being executed. On the other hand, cin.get() accepts the enter key as valid input.But perhaps more importantly is the second phenomena that occurs when more characters are placed into the input stream (cin) than are read out. When asked for a letter in the above program, enter more than one letter and watch what happens.
Let’s say you enter “abcde”.
cin >> buf[0]reads the ‘a’ character, but “bcde” are still left in the input stream. Consequently, when the code gets tocin >> chIgnore, it reads the waiting ‘b’ character out of the input stream and doesn’t pause at all!The 3 step process is a little more foolproof. First,
cin.clear()clears any errors the user may have caused by providing invalid input in the past. Second,cin.ignore(255, 'n')gets rid of up to 255 waiting characters in the input stream (or until a n is encountered), which is almost always going to be enough to clear out the input stream. Finally, we usecin.get()to wait for a character. Since we just cleared the input stream, there are no characters waiting. Consequently, the program will wait for the user to enter something.In 99% of the cases you encounter,
cin >> myVariablewill probably work exactly as you expect. But since the 3 line method is generally more foolproof and isn’t particularly burdensome to implement, I’d say it’s the superior solution.That helps a lot.
Very cool.
I made a comment here about endl, with a different name. Tiomon.. the infamous typo..
I kept getting an error because instead of endl (lowercase L) I put end1 (ONE). I think you should put this up there since even though it’s humiliating I took a “little” while trying to fix it (thanks to Google..) someone else might encounter the same thing I did.
[ That's a great point. I'll add it to the FAQ. I added some additional advice in the answer to this issue. -Alex ]
If you’re using Dev-C++, you can put on the end of main function (before return 0;) system(”PAUSE”); to don’t close console window immediately. This command pause the program and wait to keypress. But I think that it works only in MS Windows.
I’ve been learning C++ for a while now but you can also put this code at the end of your file and before return 0; in the main function to keep it running and then enter y or n to quit or not, respectively:
char quitKey = 'y'; do { cout << quitKey; } while (quitKey != 'y');I find some of these very helpful..thanks.
Just a note to Alex; at the beginning when you present the cin.ignore way of pausing a program, you accidentally wrote ‘\n’ instead of ‘n’. Just so you know ;-) Otherwise, perfect guide! Thanks :-)
[ Thanks! Fixed. -Alex ]
hi!, i just have a question on how to convert a nuber
to a roman numeral and to character,,,,
example when i enter “10″ the output must be “X” but what if i entered i large
number?, how will it it print its value if it is too long?
thats just a question…..
pls give me an idea,,,,
i really need to solve that but i cant,,,,,
thanks,,,,
pls. email me..
better if you include the main program
thanks…….
These types of questions are better posted in the forums.
I am beginning programming so I am curious about the identifiers used in include files.
Should I learn which identifiers I can use from include files? Is it possible to list identifiers from include files and what
they are doing (like cout in iostream.h)? Or is it just expierence to know which identifiers I can use? How do I know which
file to include in my code when using an identifier?
Thanks,
Niels
It’s sort of a mix of things — if you wrote the headers yourself, you probably have an idea what identifiers they include. For things like the standard library, a good reference should tell you which headers to include for which things. For third party libraries, you’ll either have to consult the documentation or actually look in the headers yourself.
Another question.
How does the compiler knows the location of the include files?
Niels
Generally your project will have a project directory or source directory that will be the home for your source code files by default. You can use relative pathing to include files in child or parent directories from there. Also, most (all?) compilers give you the option to add directories to your
“include path” — these directories will be searched if the compiler can’t find a file in the current project directory. In this way, you can add 3rd party libraries to your include path and not have to copy the files directly into your projects when using them.
#include <iostream> #include <conio.h> <----- using namespace std; void main() { cout << "Hello world !"; getch(); <------ }is it better to use getch ? =/ seems shorter to me
i’m a beginner too, but as i’ve tried compiling your program. There seems to be an error on “void main()”
and the error is resolve as soon i changed it to int main()
what’s the difference?
Technically, main() is supposed to have return type int. However, many compilers will let you get away with returning type void instead (they do an implicit return 0 at the end of main). I guess you found one of the compilers that doesn’t let you do that. :)
It’s generally a good idea to have main() return an int. It’s guaranteed to be compatible across all compilers, whereas a return type of void on main() is not.
conio.h is not part of the standard C or C++ language, and many compilers don’t support it. It may work on your compiler, but you should generally using it, as your code will not be properly compatible.
It works with VC++ 08 and stays open,
but when i try to open the “HelloWorld.exe” it closes right away, and i dont understand how to add the other stuff caus eeverytime i try it does not work, coul you show me a pic?
Wonderful tut mate!
I use Xcode and I tried every code that you have for the HelloWorld, but it always comes with the same error. “failed with exit code 1″ Could you help me?
im planning on learning cpp but one question is it any good if your not doing like visual programming i mean like gaming or should i rather learn java can u tell me some pros and cons for each.? thanks
I’m not a Java guy, so I couldn’t fairly compare and contrast the languages. Do a google search and I’m sure you’ll find plenty of people who are willing to make the comparison.
I have the same problem as Christian, When i Open helloWorld from Debug: Start without debugging, the program opens fine, but then i try to run the .exe from the folder it opens for like 0.1 of a second and closes, what should i do?? please respond
I have no idea why it wouldn’t be working. What compiler and OS are you using?
I am using microsoft visual C++ 2008 express edition, and my OS is Windows XP. The program opens fine when I run it from Debug: Start without debugging, it opens the way it should open and stays there until I close it, But when i run the .exe file from my HelloWorld folder in my VC2008Projects folder it opens for like 0.1 of a second and closes. What is the problem?? If you want I can take some screen shots to clerify more. Plz respond!
Are you using the following code at the bottom of main():
?
I had the same problem as Tassy (When I ran the .exe file)
… it only took me an hour to find this comment.
Why does the program run in Microsoft Visual C++ 2008 Express Edition and produce a pause with the result showing in the cmd prompt window, BUT not when you run the .exe program?
BTW: Great job with this tutorial.
It’s easy to understand and your responses to all our comments/questions is an awesome and appreciated committment. Thank you.
I think I found the solution to his problem, because I ran across it just now too.
It’s a really simple thing, it’s not even coding related:
In the 2008 version, they changed around the hotkeys. So F5 is not ‘run without debugging’ but it’s ’start debugging’. ‘Run without debugging’ has become ctrl+F5 instead.
So someone pressing F5, as is recommended in the tutorial, will start debugging, in which case, for me at least, it doesn’t work. However, choosing ‘run without debugging’ from the debug menu does help.
Apparantly someone at miscrosoft thought that it would be more userfriendly to have debugging accessed more quickly…
I hope this helps.
No I am not using:
cin.clear();
cin.ignore(255, ‘n’);
cin.get();
Because I thought you said that code should be added only for users who are using Deviant, and not Visual Studio? Or Am I wrong?? Anyways I am using visual studio C++ 2008 and I have the code written exactly as you told in the tutorial:
#include “stdafx.h”
#include
int main()
{
std::cout << “Hello world!” << std::endl;
return 0;
}
Should I add those extra 3 lines of code?? Because I thought thats only for Deviant, anyways can you please respond back thx :)
I don’t even know what Deviant is. :)
If your program automatically closes after running it, then add those lines and it won’t any more. They should work regardless of compiler, IDE, OS, etc…
Can I buy these tutorials on CD or something?
Thanks for having these tutorials! I like it ;)
Nope, not at this time, unfortunately. At some point I’d like to do a book, but that’s far in the future. Sorry :(
the easiest, simplest, and just plain best way to make a c++ program pause is to just put
at the end of the main function.Note that in order for this to work you must have the statement
at the top of the code and
just before the main function.
Unfortunately this won’t work if there are already characters in the cin input buffer. In that case, the cin.get() will just read the next char out of the buffer and not stop.
That’s the purpose of the other two lines — to clear the input buffer so that cin.get() will stop to ask you for more input.
The best way of doing this is putting a breakpoint on the return 0; line.
If you want to run the executable file and see the results just start a console ( start – run…- “cmd” ), go to your executable file directory (using “cd dir” without quotes) and type the name of your program.
Sorry but I have no idea where I’m meant to put:
cin.clear();
cin.ignore(255, ‘\n’);
cin.get();
I don’t know what you mean by “add the following code at the end of the main() function (right before the return statement)” since there isn’t a “;” at the end of “main()”, right? If I put the above lines of code right after main() I just get a bunch of errors. If I remove the three lines, it compiles properly but closes after outputting. Can you show those three lines of code within other code to show exactly how it should look please?
Sorry, I’ve figured it out now. I misread something on Wikipedia and ended up thinking that the return statement was “;”. I’d better pay more attention in the future!
You could pause your program using the command before return 0;
The pause command:
system(”PAUSE”);
doubled “Problem 4″ and answer for first “Problem 4″ not marked as “Answer 4″
(please remove my comment after patching)
This one’s right Alex. I don’t know if he was clear though…
Should be…
Ok, so I see that many people have had problems with running their .exe file rather than running the project straight from the IDE.
My problem precludes this. How exactly do I link the .obj files to create the .exe? (I am using Visual C++ 2008.) I didn’t see any instructions in the previous subchapter, and since I’m a newb I couldn’t figure it out. Thanks.
You need to use your compilers Linker. I don’t know what VC++ uses as a linker, to be honest. I always use gcc, so I couldn’t help you on that one (heck, I’m on a Linux computer, so I wouldn’t even be able to download VC++ to try it out). However, MSDN has some information on using the VC++ linker, called LINK. It should be as easy as navigating in the command prompt to the folder with your .obj files, then saying “link /OUT:MyProgName.exe MyObject1.obj MyObject2.obj”.
Though, then again, if you’re using Visual Studio, there should be a very easy “Compile and run” button in there…
Also, Why does the solution to the 3rd problem work? What exactly does the solution accomplish?– You know, in a behind the scenes mechanical sense?
(Sorry I missed my window of time for editing my previous post.)
When you declare “using namespace” you tell the compiler that, in the event that it cannot find the function or object in the global scope (the global namespace), that it should try placing the namespace(s) provided before in front of the function or object. For example, you can choose to either do it this way…
int main() { using namespace std; cout << "Hey \n"; cout << "You \n"; cout << "There \n"; }Or this way…
int main() { std::cout << "Hey \n"; std::cout << "You \n"; std::cout << "There \n"; }There’s more information about namespaces, and the reasoning behind them, on the namespaces lesson of this site.
When I compile and run the program, it will not start. I restart the program, but it automatically shuts down again. I do not know what is wrong.
whenever i try to compile my Code::Block logs say, “HelloWorld – Debug” uses an invalid compiler. Skipping… Nothing to be done.
its annoying as can be, im positive its in the right directory for the compiler, and its using the g++ compiler. Im running the new patch for Mac OS X :/
help
Look into trying Xcode instead. But to get this particularly annoying problem to work, “mariocup” wrote an answer for just the same question on the Code::Blocks forums. Make absolutely sure that g++, gcc, make, and all of those other files are located within the folder that Code::Blocks is looking under (usually it’s in /usr). I’m not positive, but I’m fairly sure the Mac OS X uses the same (or very similar) file system as Linux does, since they’re all based on Unix (either directly or simply inspired by).
Xcode worked thanks!
With problem 1, I noticed that if the line
wasn’t seperated by a whole line from the rest of the code, the program would exit immedately, without waiting for a keypress.
Learn to program in C++ in http://jmdesignstudio.kinssha.org/
access directly the link of tutorial
http://jmdesignstudio.kinssha.org/tutoriels_detail.php?table=tutoriels&id=40
Guys, This Site rocks, but dont take it as a very big problem if you are just a beginner, there was no such site as this one and I learned VISUAL BASIC 2008 EXPRESS EDITION, very useful. Keep trying and never stop doing this tutorials until you reach your aim, good luck.
I am using the beta release of Visual Studio 2010 and my console apps were exiting without waiting. Your answer to problem #1 has to be modified to work with this release: “std::” has to be added before “cin” or it won’t compile.
Sorry…if I had read the part that said to use “using namespace std;” I wouldn’t have made this comment.
I am also using the beta release of Visual Studio 2010 and my console apps are exiting without waiting.
I have read and tried everything in all the posts and tutorial with no success
Bruce can you post your code?
Any help would be appreciated
Thanks Charlie
I suggest to use a book rather than a online tutorial for C++ because .C++ is need to be carefully learned unlike Visual Basic ,if u mess up then u may bored to proceed