problems after compiling C++ with the G++ compiler

Asked

Viewed 95 times

-1

I have a problem here after compiling a program in C++ using the compiler g++, after compiling everything, I try to open the executable file, then open my windows cmd (using windows 10)When the terminal starts to show something it automatically closes, how do I fix it? I have tried using getch() and scanf() functions but nothing happened

PROGRAM

#include <stdio.h>
void main(){
    printf("Teste");
}
  • You can put the program ?

  • Ready, I’ve put the program

1 answer

1

Yes, this is the expected same, after all has no loop holding or "pause" to avoid, the program runs what has to run and delivers the main() then the process ends and the window closes, that is the exactly expected effect, it is no problem with the compiler but with its understanding.

Program with graphical interface does not close because it has an internal "loop" (+or-like), which prevents completion of the process while the window is open.

If you want to prevent the window from closing just use pause (in windows I believe)

#include <stdio.h>  /* printf */
#include <stdlib.h> /* system */

void main(){
    printf("Teste");
    system("pause");
}

Or an example you can do is drag your executable after compiled into the cmd, squeeze the Enter on the screen of cmd the answer will appear:

teste


getch, getche and getchar

Waits to type something to finish:

#include <stdio.h> /* printf */
#include <conio.h> /* getch */

int main() {
    printf("teste");
    printf("\nPressione qualquer tecla para finalizar");
    getch();
    return 0;
}

Waits to type something and sends what was typed to the output:

#include <stdio.h> /* printf */
#include <conio.h> /* getch e getche */

int main(){
    printf("teste");

    printf("\nDigite uma letra ou numero:\n");
    getche();

    printf("\nDigite qualquer coisa para finalizar");
    getch();
    return 0;
}

However, according to this reply /a/75216/3635, use of anything related to conio.h might not be reliable, so use getchar:

#include <stdio.h>

int main ()
{
    printf("Digite algo:");

    getchar();
    return 0;
}

If you need to take the exit:

#include <stdio.h> /* printf e getchar */

int main (){
    printf("Digite algo:");

    int test = getchar();
    putchar(test);
    return 0;
}
  • obg, I’m a beginner, but thanks for the attention

  • @Lucasgabrielsanches if an answer solved the problem please mark it as correct. Read: https://pt.meta.stackoverflow.com/a/1079/3635

Browser other questions tagged

You are not signed in. Login or sign up in order to post.