开发者

Keeping Console Window Open in Visual Studio (C)

开发者 https://www.devze.com 2022-12-16 13:08 出处:网络
I usually use XCode but was having a problem opening a file with this code: #include \"stdafx.h\" #include <stdio.h>

I usually use XCode but was having a problem opening a file with this code:

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

int main(void )
{
   printf("Hello");
   FILE *filePtr;

   filePtr = fopen( "test.txt", "r" );
   if (filePtr == NULL)
   {
      fprintf(stderr, "Can't open \"test\"\n");
      exit(EXIT_FAILURE);
   }
   else
   {
      int x;

      printf("File open successful\n");
      /* read one character at a time until EOF is reached */
      while ((x = fgetc(filePtr)) != EOF)
      {
         //printf("%c", x);
         fprintf(stderr, "%x\n",x);
      }
   }
   fclose(filePtr);
   system("pause");

   return EXIT_FAILURE;
}

The console window closes so fast and at the bottom bar of VS it says: "'C_test.exe': Loaded 'C:\WINDOWS\WinSxS\x86_Microsoft.VC90.DebugCRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_f863c71f\msvcr90d.dll' The program '[1116] C_test.exe: Native' has exited with code 1 (0x1)." What does that mean?

Also, ca开发者_Go百科n anyone point me to good VS starting points / tutorials?


See also How to keep the console window open in Visual C++?


The reason you can't see it is because there is no possibility for your program to pause during execution. In Visual Studio the typical behavior is to close the console window the second the program has completed its execution.

The bottom bar is telling you that the program complete and what the return value was (1 in this case).

What I would also do is add code right before the exit point of the program with #ifdefs:

#ifdef VS_DEBUG
fgetc(STDIN);
#endif

Now your program will pause when it's done and wait for a keypress then close the window.

I'm sure there is also a way in the project settings to prevent the closing, I've never looked myself.


I generally leave a breakpoint on the closing brace of main, so that the output of my window is visible while debugging, but Visual Studio will keep the console window open if you start the program without debugging (Ctrl+F5). Alternatively, you could simply ask for input, @MadcapLaugher's fgetc(STDIN); is probably your best bet - though I would add a prompt: "Press any key to continue... "


 #include<stdio.h>
 int main() 
{

    printf("Hello World from visual Studio \n");

    //to prevent console window temination 
    system("pause");

    return 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号