0

I have a piece of code that should output some text, but when I run it an empty window pops up. I want to create characters on a window. Can someone tell me why this doesn't happen?

Here is the code:

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

using namespace std;

int main() {
    char str[] = "Hello C++";

    cout << "Value of str is : " << str << endl;

    return 0;
}

Thanks

Borgleader
  • 15,826
  • 5
  • 46
  • 62
strax
  • 11
  • 3
  • Do you mean that the window closes immediately or that the text doesnt show up? If it's the latter, [I cannot repro](http://coliru.stacked-crooked.com/a/78421fbe85a5a59f). If it's the former try Ctrl+F5 (assuming VS due to stdafx.h) – Borgleader Mar 31 '17 at 13:04
  • Does the empty window stay there or does it go away really quick? – NathanOliver Mar 31 '17 at 13:04
  • Are you using Visual Studio? – harper Mar 31 '17 at 13:05
  • 1
    This is impossible. It actually _does print stuff_ and closes too quickly for anyone to see it. – ForceBru Mar 31 '17 at 13:05
  • Possible duplicate of [Preventing console window from closing on Visual Studio C/C++ Console application](http://stackoverflow.com/q/1775865/3425536) – Emil Laine Mar 31 '17 at 13:07
  • @Incomputable It does not have to be. `char name[] = "...";` is perfectly legal. – NathanOliver Mar 31 '17 at 13:10
  • @NathanOliver, but trying to modify is UB, right? [According to this](http://stackoverflow.com/questions/2245664/what-is-the-type-of-string-literals-in-c-and-c) – Incomputable Mar 31 '17 at 13:11
  • @Incomputable Nope. `char name[] = "...";` is short for `char name[4] = {'.', '.', '.', '\0'};` and is mutable. – NathanOliver Mar 31 '17 at 13:12
  • @NathanOliver, oh, I got it now. So, `char* str = "..."` has to be const, right? The array version just initializes the contents with the contents of the array – Incomputable Mar 31 '17 at 13:15
  • @Incomputable Correct. `char* str = "..."` is ill formed. The array form is not. – NathanOliver Mar 31 '17 at 13:17

1 Answers1

-1

Your code is fine -- but the window will automatically close when the code finishes its execution.

Consider adding a cin at the end of your code to prevent the window from closing.

int t;
cin >> t;
AlexG
  • 1,091
  • 7
  • 15
  • 2
    As far as I am concerned, I **hate** this trick. It adds in the source something that only concerns the development environment and clutters code when you have more than one exit line. Any decent IDE has an option to not close the terminal window, even MSVC. The correct way is to use Ctrl-F5 or put a breakpoint on last line of main (which should be a `return x;`) and on other possible exits. – Serge Ballesta Mar 31 '17 at 13:11
  • @SergeBallesta given the simplicity of that code I don't think that's much of a dealbreaker.. – AlexG Mar 31 '17 at 13:17
  • Doesn't matter if the code is simple or not, there are much better solutions to this problem as Serge has pointed out. – Borgleader Mar 31 '17 at 13:23