Search

0.7 — A few common C++ problems


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:

Second, add the following code at the end of the main() function (right before the return statement):

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:vcprojectstest.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 (or more) of your C++ code files does not include the stdafx header as the first line. To fix this problem, simply locate the file(s) producing the error (in the above error, test.cpp is the culprit), and add the following line at the very top of the file(s):

Note that for programs with multiple files, every C++ code file needs to start with this line.

Alternatively, you can turn off precompiled headers.

Problem 3: When trying to use cin, cout, or endl, the compiler says cin, cout, or endl is an “undeclared identifier”

Answer 3: First, make sure you have included the following line near the top of your file:

Second, make sure cin, cout, and endl are prefixed by “std::”. For example:

Problem 4: When trying to use endl to end a printed line, the compiler says end1 is an “undeclared identifier”

Answer 4: 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 non-programming fonts.

Problem 5: My program compiles but it isn’t working correctly. What do I do?

Answer 5: 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.

Problem 6: How do I turn on line numbering in Visual Studio?

Answer 6: Go to the Tools Menu, and choose Options. Under the Text Editor submenu, choose All Languages (or C/C++), and you’ll see a checkbox on the right for Line numbers.

Problem 7: When I compile my program in Visual Studio 2010, I get an error message about a COFF file being invalid. How do I fix this?

Answer 7: If you see the following error when compiling with Visual Studio 2010:

LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt

You’ve encountered a Microsoft OS/compiler incompatibility. It has nothing to do with your code.

The best first option is to download and install Visual Studio 2010 Service Pack 1.

If that does not fix your issue, there are many other good suggestions on Stack Overflow about the various causes and solutions to this problem.

I have some other problem that I can’t figure out. How can I get an answer quickly?

Answer: As you progress through the material, you’ll undoubtedly have questions or run into unexpected problems. The best and fastest place to get answers to your questions is on a site designed for programming questions and answers, like Stack Overflow. Try posting your question there. Remember to be thorough about what your problem is, and include all relevant information like what OS you’re on and what IDE you’re using.

1.1 — Structure of a program
Index
0.6 — Compiling your first program

52 comments to 0.7 — A few common C++ problems

  • Jason

    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”);

    • Alex

      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.

  • foq

    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.

  • Jason

    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 >> myVariable is not the best way to pause:

    First, cin >> chIgnore ignores the enter key if the user does not provide any other input. You can verify this by hitting enter when the cin >> chIgnore line 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 to cin >> 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 use cin.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 >> myVariable will 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.

  • Timon

    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 find some of these very helpful..thanks.

  • Niels

    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.

  • Niels

    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.

  • asdfk

    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.

  • Howard

    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.

          • Thera

            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…

  • Juan

    Can I buy these tutorials on CD or something?
    Thanks for having these tutorials! I like it ;)

  • 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.

  • Teclo

    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?

    • Teclo

      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!

  • GlassJoe

    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.

    • Quinn

      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…

  • GlassJoe

    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.)

    • Quinn

      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…

      Or this way…

      There’s more information about namespaces, and the reasoning behind them, on the namespaces lesson of this site.

  • Cameron

    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

  • viccos

    First I just wanted to say thank you so much for this site. You have really created something special here. As a completely self-taught IT professional I owe my living to people like you and this ranks amongst the best tutorials I have come across in any field.

    With that said I thought you might like to know about a pit-fall I… er… fell into.

    Having successfully run my program once I got excited and tried a few variations. I then found that my program had started blinking up for a fraction of a second and vanishing. I tried all of the things you suggested and then hit the web.

    Half an hour later I realised I was now pressing F5 instead of Control + F5 to run my program. Stupid error on my part but might be worth mentioning in the tutorial with an explanation of why you use Control+F5 rather than just F5 :)

  • zac123

    couldnt get this to stay open. using c++ 2010 express.

    after reading through the comments herei got it to work with this:

    // HelloWorld.cpp : Defines the entry point for the console application.
    //
    #include “stdafx.h”
    #include
    using namespace std;
    int main()

    {
    std::cout << "Hello world!" << std::endl;
    cin.get()
    ;
    }

    thanks for this brilliant web site. ive just started learning c++ sp this will be very useful!

  • mezz

    Would you say this tutorial would be improved if it was explicit in naming, e.g., instead of using using namespace std; using the “std::” reference? I’m just wondering because I’m being told it is OK, but better to future-proof and avoid any inherited name collisions.

  • Vignesh

    for all those using dev c++ , this code will work and pause you screen until you enter a character

    #include
    using namespace std;
    #include

    int main()
    {
    cout<<"hello world!!";
    getch();
    return 0;
    }

    the getch(); is defined in conio.h and takes a character from input without printing to screen. you can see the output until you press a key.

    just saying even system("pause") will work except that it prints "Press any key to continue" .

  • Hi. I am new to CPP. I used to have this problem of the output flashing and disappearing, but a friend told me to use clrscr() after declaring the variables and getch(); just before the closing braces of the program. Now, the output stays put until I press enter. I just want to know what exactly the getch() function does…
    I’d love it if you explained. :-)

    • TonyArra

      For anyone else interested in this question:

      clrscr() and getch() are part of the conio.h library (non-standard library that won’t come with most compilers and is not available on Linux).

      clrscr() just clears the console screen.

      getch() is a variant of the standard getchar() function. getch() waits for the user to press any character on the keyboard. The function returns the character, but doesn’t print the character to the screen like getchar() does. It also does not require the user to press the Enter key in order to submit the character (this is convenient because you no longer need to flush the standard input stream).

      On Linux, you can get similar functionality by installing the curse.h library.

  • Nexus

    As an alternative (and sometimes better) solution for Problem 3:

    std::cout << "Hello World" << std::endl;

    This is good to use when you are using multiple namespaces (I know a bit of C++, I am just starting from the beginning to make sure I get everything), but for now it may be good just to type:

    using namespace std;

    As they suggest. I just wanted to put that out there so that people know about it before they get too solidified with the idea of using the already suggested solution.

    You can view a short video by XoaX.net about namespaces here:
    https://www.youtube.com/watch?v=9oWhQy_hW-k
    It is about 3 minutes long.

  • Captain Obvlious

    Recommending the use of using namespace std; is itself a problem, especially if you are doing at global scope and definitely if you do it in a header file.

  • James

    I see the responses here started back in 2007. It is now 2015. That’s eight years… so where’s the book?
    :)
    Thanks for the great tut.

  • Daniel Ahn

    well i don’t get what you mean by:
    Second, add the following code at the end of the main() function (right before the return statement):

    [1cin.clear();
    2cin.ignore(255, ‘n’);
    3cin.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.

    i tried to put is just right before return0;
    just what ever but it shows bunch of error
    and when i press ctrl and F5 together it will stay but when I click debugging it closes immediately

  • Maria

    but output screen still blink after writing these lines….

Leave a Comment (Note: put C++ code inside [code][/code] brackets)

  

  

  

12 − five =

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">