Alternative to system ("PAUSE") c ++

2

Hi, I am looking for an alternative to system ("PAUSE") because for my program to be completed correctly I usually introduce this sentence. Normally a program in c ++ usually has the following format:

#include <iostream>

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    return 0;
}

I will start asking some expert in c ++ which means exactly return 0 because when the sentence skips the program ends, I think it is its function but I am wrong. Then I have a program that I need to use system("PAUSE") so that the exception does not skip, otherwise the program does not complete, that is, it fails and it can not finish. So what alternative to system("PAUSE") recommend me to use so that the program does not close and end correctly ..

    
asked by Perl 15.11.2016 в 17:55
source

4 answers

4

About return . When a program is run, there is always another process that he is the one who throws it. The terminal itself can be the process that launches your program, the operating system if it is a system service, etc. In case of Dev-C ++ (or the IDE you're using), I can assume that the process Dev-C ++ launches a new terminal, and that terminal process is who launches your program.

The return serves to return, to the process "that you threw to me", a value indicating whether the process ended satisfactorily or not. Return 0 means that your program ended successfully, and a different value of 0 It means no.

For example, suppose you have a program that receives a value from the user, which it must be a number greater than zero for its natural operation. If it is received a number >0 , the program does what it has to do, and if not, the program can not do its homework, so it is considered a wrong situation and it is notified. The code would be, for example, the following:

int main()
{
    int i;

    std::cin >> i;

    if (i <= 0)
        return 1; // Problema.
    else {
        // Código para el funcionamiento normal del programa.
        return 0; // El programa terminó satisfactoriamente.
    }
}

In this way, when your process is executed, when it finishes, the process that has call to your program you can know if your program ended satisfactorily or do not. Obviously, you can return the value you want. For example, you can indicate different return values to indicate the type of specific error:

int main()
{
    int i;

    std::cin >> i;

    if (i == 0)
        return 1; // Se recibió un cero.
    else if (i < 0)
        return 2; // Se recibió un uno.
    else {
        // Código para el funcionamiento normal del programa.
        return 0; // El programa terminó satisfactoriamente.
    }
}

With those return values, the calling process (if you know what each means return value of your program), can act in one way or another according to the specific error produced.

If your program does not have a return sentence, the compiler adds you a return 0; at the end of your program:

int main()
{
    // Código del programa.

    // return 0; // Implícito si no lo escribes tú.
}

Now, what is the system("pause") worth? The system function allows you to execute any command that accepts the terminal language of your system operative For example, in Windows, within system , I can put any command in DOS language. On Linux, you could write any command written in Bash , for example.

Why do you need system("pause") ? As it turns out, Dev-C ++ , by default, When you finish your program, close the terminal that Dev-C ++ opened for Run your program. When calling system("pause") , the program crashes until the user types something. In this way, you keep the terminal open and you can see the result of your program until you click on a button.

In CodeBlocks , if I'm not wrong, you would not need the system("pause") , given that CodeBlocks , by default, does not close the terminal when it finishes program.

Conclusion: The fact that your program is closed, and you do not see the result,   it's not because any kind of exception is being thrown, but because you   program ends correctly and Dev-C++ has closed the terminal. The   value of return has nothing to do here. You could remove it (the compiler   you would re-add it), or change the return value, that the result you will see   it will be the same. system("pause") allows you to make your program wait for   the user presses a key, and therefore, keeping the terminal   open system("pause") only you need in some IDEs ( Dev-C++ ) and    pause is an exclusive Windows system command. On Linux pause no   It exists.

NOTE: A non-zero return value does not mean that your program contains errors, or that the program has failed from an internal point of view. The program ends well from a fully functional point of view regardless of the return value. That is, the process ends cleanly, just that a non-zero return value indicates that "the process has finished well but has not been able to do what it is supposed to do".

    
answered by 15.11.2016 в 18:45
3

If the reason to look for an alternative to system(“PAUSE”) is only the observe the exit , the responses of Peregring-lk and eferion explain the options very well.

However, if what you want is to avoid using system(“PAUSE”) for any of the following reasons:

  • Because it is dependent on the Operating System (it exists in Windows / DOS but not in Linux / Unix)
  • Because misuses resources (it's expensive in terms of processing)
  • It should instead implement solutions in native C ++, for example:

    cin.get();
    

    Which makes the program more efficient, and prevents bad practice (although quite common).

    The structure of a program would be like this:

    #include<iostream>
    using namespace std;
    
    int main()
    {
        // programa
    
        cout<<"Fin del programa" <<endl;
        cin.get(); // hace que la ejecucíon se detenga hasta que se presione enter
    
        return 0; 
    }
    

    Note: the native C equivalent, to achieve this is:

    getchar();
    
        
    answered by 15.11.2016 в 19:39
    2

    If you are in Windows environment you can use:

    #include <conio.h>
    
    std::cout << "Pulse una tecla para continuar...";
    _getch();
    

    If you are in Linux you can try the library curses :

    std::cout << "Pulse una tecla para continuar...";
    getch();
    

    Also, browsing the English version of StackOverflow, I found a thread in which they propose another alternative:

    #include <termios.h>
    #include <stdio.h>
    
    static struct termios old, new;
    
    /* Initialize new terminal i/o settings */
    void initTermios(int echo) 
    {
      tcgetattr(0, &old); /* grab old terminal i/o settings */
      new = old; /* make new settings same as old settings */
      new.c_lflag &= ~ICANON; /* disable buffered i/o */
      new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
      tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
    }
    
    /* Restore old terminal i/o settings */
    void resetTermios(void) 
    {
      tcsetattr(0, TCSANOW, &old);
    }
    
    /* Read 1 character - echo defines echo mode */
    char getch_(int echo) 
    {
      char ch;
      initTermios(echo);
      ch = getchar();
      resetTermios();
      return ch;
    }
    
    /* Read 1 character without echo */
    char getch(void) 
    {
      return getch_(0);
    }
    
    /* Read 1 character with echo */
    char getche(void) 
    {
      return getch_(1);
    }
    
    /* Let's test it out */
    int main(void) {
      char c;
      printf("(getche example) please type a letter: ");
      c = getche();
      printf("\nYou typed: %c\n", c);
      printf("(getch example) please type a letter...");
      c = getch();
      printf("\nYou typed: %c\n", c);
      return 0;
    } 
    
        
    answered by 15.11.2016 в 18:02
    0
    system("pause"); 
    

    It is not a function which is a standard to use in any program so that it does not close, the correct thing as in any windows application is to do it well, you need the program to be attentive to the user's requests, I recommend you Meanwhile, learn more about the windows API, and read about messages sent by the user:


    Now it is not necessary if you are just learning and you do not have much advanced knowledge, for it is enough to add to your code:

    while(GetMessage(0, 0, 0, 0));
    

    This will make you aware of the user's messages, which you can learn over time, if you always keep in mind that this is placed at the end of the principal before the return:

    #include <windows.h>
    
    int main()
    {
        // do some stuffs...
        while(GetMessage(0, 0, 0, 0));
        return 0;
    }
    

    Editing: I have put this for the reason that this function system("pause"); is a standard of windows, which is very logical that refers to windows.

        
    answered by 16.11.2016 в 13:09