Search

Meta

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 and should be avoided.

Note: Visual Studio will not pause at the end of a console application if it is run with debugging (Debug Menu->Start Debugging). If you want it to pause, you can either use the code solution above, or run your program without debugging (Debug Menu->Start Without Debugging).

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 lesson 1, specifically sections 1.11 and 1.11a..

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 this Stack Overflow thread about the various causes and solutions to this problem.

Problem 8: When I compile my program, I get an error about unresolved external symbol _main or _WinMain@16

Answer 8: This means your compiler can’t find your main() function. All programs must include a main() function.

There are a few things to check:
a) Does your code include a function named main?
b) Is main spelled correctly?
c) Is the file containing main part of your project? (if not, either move the main function to one that is, or add the file to your project. See lesson 1.8 -- Programs with multiple files for more information about how to do this).
d) Is the file containing function main set to compile? (Also see lesson 1.8 -- Programs with multiple files for more information about how to do this).

Problem 9: When I compile my program, I get a warnings about “Cannot find or open the PDB file”

Answer 9: This is a warning, not an error, so it shouldn’t impact your program working. However, it is annoying. To fix it, go into the Debug menu -> Options and Settings -> Symbols, and check “Microsoft Symbol Server”.

Problem 10: I’m using Code::Blocks or g++ on the command line, and none of the C++11 functionality works

Answer 10: For Code::Blocks, go to Project->Build options->Compiler settings->Compiler flags and check “Have g++ follow C++11 ISO C++ language standard”

For compiling with g++ on the command line, add the following to the command line: -std=c++11

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.6a -- Build configurations

73 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….

  • cmpj

    in code blocks
    on windoes where i compile it
    this is what i get

    “helloworld - Debug”: The compiler’s setup (GNU GCC Compiler) is invalid, so Code::Blocks cannot find/run the compiler.
    Probably the toolchain path within the compiler options is not setup correctly?! (Do you have a compiler installed?)
    Goto “Settings->Compiler…->Global compiler settings->GNU GCC Compiler->Toolchain executables” and fix the compiler’s setup.
    Skipping…
    Nothing to be done (all items are up-to-date).

    • Alex

      As the error message says, do you have a compiler installed? Code::Blocks comes in different configurations -- some of them don’t come with compilers. If you’re running on Windows, make sure you download the mingw version.

  • razan

    this is what i get

    1>---- Build started: Project: helloword, Configuration: Debug Win32 ----
    1>  helloword.cpp
    1>c:\users\danny\documents\visual studio 2010\projects\helloword\helloword\helloword.cpp(6): fatal error C1083: Cannot open include file: ‘ isotream': No such file or directory
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

  • razan

    ‘helloword.exe': Loaded ‘C:UsersdannyDocumentsVisual Studio 2010ProjectshellowordDebughelloword.exe’, Symbols loaded.
    ‘helloword.exe': Loaded ‘C:WindowsSysWOW64ntdll.dll’, Cannot find or open the PDB file
    ‘helloword.exe': Loaded ‘C:WindowsSysWOW64kernel32.dll’, Cannot find or open the PDB file
    ‘helloword.exe': Loaded ‘C:WindowsSysWOW64KernelBase.dll’, Cannot find or open the PDB file
    ‘helloword.exe': Loaded ‘C:WindowsSysWOW64apphelp.dll’, Cannot find or open the PDB file
    ‘helloword.exe': Loaded ‘C:WindowsSysWOW64msvcp100d.dll’, Symbols loaded.
    ‘helloword.exe': Loaded ‘C:WindowsSysWOW64msvcr100d.dll’, Symbols loaded.
    The program ‘[3496] helloword.exe: Native’ has exited with code 0 (0x0).

    • Alex

      This is a warning, not an error, so it shouldn’t impact your program working. However, it is annoying. To fix it, go into the Debug menu -> Options and Settings -> Symbols, and check “Microsoft Symbol Server”.

  • Batuhan

    ok nice points

  • Jimmy

    Regarding problem 1:
    When I use this code in my program, I have to press enter TWICE to quit the program. It seems that in case of an empty input stream, the function cin.ignore() waits for some key to be pressed. So, I have to press enter for ignore() and then again for get(). Am I doing something wrong?
    I tried using cin.peek() to check whether input stream is empty or not:

    but it didn’t work - the body of ‘if’ instruction executes always anyway, just as if peek() didn’t return EOF (when it should, cause the input stream is obviously empty).
    Any help?

    • Alex

      Some IDEs will automatically pause the program at the end of execution. Since yours appears to be one of the ones that does this, I’d suggest not using the code to make the program wait at the end. :)

      • Jimmy

        I’m sorry, it seems that I wasn’t specific enough. It’s not a matter of IDE. What I described happened without any IDE (text editor + manual compilation on command line). When I tried this in CodeBlocks I had to press enter 3 times to quit (twice for my program and once for CodeBlocks’ final pause).

        It’s not a big deal, I can totally live without this :) I’m just curious why it won’t work.

  • ChinmayP

    hey Alex, great tutorial. i was doing the first comprehensive quiz and encountered a problem.cin, cout,and endl seem to be not members of std.i tried using std namespace first but it didnt wor so i added std:: but it still gets those errors. Could you please point out what i’m doing wrong?
    ( i’m new to cpp and visual studio 2010 express :p )

    // basic programming1.cpp : Defines the entry point for the console application.
    //

    #include <iostream>
    #include "stdafx.h"

        
    int readNumber()
    {
        using namespace std;
        std::cout<<" Enter number";
        int a;
        std::cin>>a;
        return 0;
    }
    void writeNumber(int a)
    {
        using namespace std;
        cout<<"you entered"<<a<<std::endl;

    }
    int main()
    {
        using namespace std;
        int sum;
        int x = readNumber();
        int y = readNumber();
        sum = x+y;
        std::cout<<"sum ="<<sum<<std::endl;
        return 0;;
            
    }

    errer i’ve been getting:

    1>---- Build started: Project: basic programming1, Configuration: Debug Win32 ----
    1>  basic programming1.cpp
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(5): warning C4627: ‘#include <iostream>': skipped when looking for precompiled header use
    1>          Add directive to ‘StdAfx.h’ or rebuild precompiled header
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(13): error C2039: ‘cout’ : is not a member of ‘std’
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(13): error C2065: ‘cout’ : undeclared identifier
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(15): error C2039: ‘cin’ : is not a member of ‘std’
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(15): error C2065: ‘cin’ : undeclared identifier
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(21): error C2065: ‘cout’ : undeclared identifier
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(21): error C2039: ‘endl’ : is not a member of ‘std’
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(21): error C2065: ‘endl’ : undeclared identifier
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(31): error C2039: ‘cout’ : is not a member of ‘std’
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(31): error C2065: ‘cout’ : undeclared identifier
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(31): error C2039: ‘endl’ : is not a member of ‘std’
    1>c:\users\svpatil.amphenol-in\documents\visual studio 2010\projects\basic programming1\basic programming1\basic programming1.cpp(31): error C2065: ‘endl’ : undeclared identifier
    ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

    • Alex

      Since you’re using Visual Studio with precompiled headers, the first line of each .cpp file needs to be:

      I think this will fix your issue.

  • Sid.

    I need help. I use Xcode on mac, but there is nothing on this page that states ANYTHING about Xcode.

  • I am getting this message "Project not compiled" every time I try to run my C++ source code. this happens even if the program where compiled successfully. what am I doing wrong? help me please!

  • Divy

    I have to press enter 2 times to end the console window with this code. However, if I comment cin.ignore, I have to press enter only 1 time.
    Why does this happen?

    PS: I am using Visual studio 2013 and running the programming by directly debugging (i.e. F5). When I start without debugging, I have to press enter 3 times(taking in count Press any key to continue..).

    One more thing. When I edited my comment, the code lost its syntax highlight. So I had to delete the previous comment and re-post again.

    Nice tutorials, thanks a lot..

    • Alex

      The cin.ignore() line is meant to clear out any extra input in the buffer so that cin.get() will pause for user input. However, if there is no input in the buffer, cin.ignore() will pause too. So you get a double pause.

      Better a double pause than no pause.

      Strangely enough, although it seems like it should be easy, due to the way C++’s input and output are implemented, I’m not sure a solution that pauses only once in all cases is even possible.

      • Divy

        I don’t understand what kind of errors does cin.clear() will clear ?

        I think a possible solution to above problem would be one statement to clear(not ignore) the input buffer and other statement like cin.get()(this moves forward only by pressing enter and we can press many other keys just before pressing enter) or getch()(this waits for only one character) to pause for user input.

        • Alex

          For example, if you do this:

          But then type in “a”, cin will “break” because you can’t assign “a” to an integer. Consequently, cin will set some error flags to let you know something went wrong. It’ll refuse to process more input until you call clear() on the flags. In other words, if cin were in a bad state, cin.ignore() wouldn’t work unless we called cin.clear() first.

          Unfortunately, I haven’t found a reliable way to clear the input buffer. There are hacks that work on some architectures/compilers, but not on others.

Leave a Comment

  

  

  

four × 4 =

Put C++ code inside [code][/code] tags to use the syntax highlighter