0

I want to do something like below, but the console closes too fast for me to read the error message and I can't break; completely out of a nested for loop. I just want the program to terminate and give me time to read the error message before it closes.

#include <iostream>
#include <string>

int main()
{
    std::string x;
    std::cin >> x;
    char y;
    for (int i = 0; i <= 5; ++i)
    {
        y = x[i];
        for (int j = 0; j <= 5; ++j)
        {
            if (j < 5)
            {
                std::cout << "Random text.\n";
            }
            else if (j >= 5)
            {
                std::cerr << "ERROR, j cannot be more than 4.";
                exit(EXIT_FAILURE);
            }
        }
    }

    return 0;
}

I've considered using cin.get(); but it's not guaranteed to work because cin may still have input from its buffer, and I don't think I can invoke it anyways after exit(); is called. Is there any way for me to have the console wait for me to press a key before terminating so I can read this error message? Or is there a better way for me to output this error message and terminate the program safely?

Note: The above program is just example code to explain what I'm trying to do.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
Wandering Fool
  • 2,170
  • 3
  • 18
  • 48
  • I popped that in before `return 0;` but the program terminates as soon as `exit();` is called and I believe the instruction `getchar();` is never executed. – Wandering Fool May 21 '15 at 02:39

3 Answers3

2

You can remove all the characters from the std::cin buffer, then call cin.get();, and only after invoke return (better than std::exit since the latter does not perform stack unwinding and does not invoke destructors for objects with automatic storage duration).

std::cin.clear(); // clear error flags
// ignore the rest, must #include <limits>
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
std::cin.get();
return -1;

Related: How to end C++ code

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • Your solution is just the one I was looking for. I completely did not know I could call another `return 0;` inside of a for loop. – Wandering Fool May 21 '15 at 02:48
  • @WanderingIdiot yes, you can, since `main` is a function that returns `int`, so it behaves as any other function. However, the convention is to return non-zero on error, but it's up to you. – vsoftco May 21 '15 at 02:48
  • @vsoftco doesn't exit() do clean up since C++11? – Steephen May 21 '15 at 03:04
  • @Steephen No, only the destructors of the objects with `static` or `thread_local` storage duration are invoked, at least that's what I read [here](http://en.cppreference.com/w/cpp/utility/program/exit). It looks like there are more guarantees in C++11, but objects with automatic storage duration are still not destructed. – vsoftco May 21 '15 at 03:06
  • Since there is only main thread does it not consider as thread_local? And automatic storage should take care by RAII, right? – Steephen May 21 '15 at 03:11
  • @Steephen No, it does not. If you don't mark it explicitly `thread_local`, the variable will be of automatic storage, not `thread_local` storage. See http://ideone.com/FfqfiQ to convince. If you uncomment `thread_local`, the destructor is invoked. Otherwise is not. And RAII works only when static unwinding is performed, or only when destructors are automatically called, but `exit` does not perform stack unwinding or destructor calls for automatic objects. – vsoftco May 21 '15 at 03:14
1

If you include both <thread> and <chrono> you can call

std::this_thread::sleep_for(std::chrono::seconds(1));

to make the present thread sleep (pause in execution) for one second.

There are numerous time steps predefined in std::chrono, so if you want more granularity, you can call one of those. The 1 in the function call specifies the number of seconds.

However, if you want to use the above syntax, you should not use a call to exit. Instead, use exceptions inside of a try block and catch those exceptions with a catch block. You can read more on try-catch blocks in c++ here and here.

jaggedSpire
  • 4,423
  • 2
  • 26
  • 52
0

This will stop your dos window from getting closed.

system("PAUSE") ;

Add this just before return statement. You can also use getch() to stop your dos window from getting terminated.

nitish-d
  • 241
  • 2
  • 11
  • 1
    this solution is not portable as it depends on the operating system "PAUSE" command, which does not exist everywhere – vsoftco May 21 '15 at 02:39