终止我的程序并让它输出我选择的错误消息的最佳方法是什么?
What is the best way to terminate my program and have it output an error message of my choosing?
我想执行如下操作,但控制台关闭速度太快,我无法阅读错误消息,而且我无法 break;
完全脱离嵌套的 for 循环。我只想让程序终止,让我有时间在它关闭前阅读错误信息。
#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;
}
我考虑过使用 cin.get();
但它不能保证工作,因为 cin
可能仍然有来自其缓冲区的输入,而且我认为我无法在 [=14] 之后调用它=] 被调用。有什么方法可以让控制台在终止之前等待我按下一个键,以便我可以阅读此错误消息?或者有没有更好的方法让我输出这个错误信息并安全地终止程序?
注意:上面的程序只是示例代码,用于解释我正在尝试做的事情。
如果同时包含 <thread>
和 <chrono>
,您可以调用
std::this_thread::sleep_for(std::chrono::seconds(1));
使当前线程休眠(暂停执行)一秒钟。
std::chrono 中预定义了很多时间步长,因此如果您想要更细粒度,可以调用其中之一。函数调用中的1
指定秒数。
但是,如果要使用上述语法,则不应使用调用退出。相反,在 try
块内使用异常并使用 catch
块捕获这些异常。您可以在 c++ here and here.
中阅读有关 try-catch
块的更多信息
您可以从 std::cin
缓冲区中删除所有字符,然后调用 cin.get();
,并且仅在调用 return
之后(优于 std::exit
,因为后者不执行堆栈展开并且不为具有自动存储持续时间的对象调用析构函数)。
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;
相关:
这将阻止您的 dos window 关闭。
system("PAUSE") ;
将其添加到 return 语句之前。
您还可以使用 getch() 来阻止您的 dos window 被终止。
我想执行如下操作,但控制台关闭速度太快,我无法阅读错误消息,而且我无法 break;
完全脱离嵌套的 for 循环。我只想让程序终止,让我有时间在它关闭前阅读错误信息。
#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;
}
我考虑过使用 cin.get();
但它不能保证工作,因为 cin
可能仍然有来自其缓冲区的输入,而且我认为我无法在 [=14] 之后调用它=] 被调用。有什么方法可以让控制台在终止之前等待我按下一个键,以便我可以阅读此错误消息?或者有没有更好的方法让我输出这个错误信息并安全地终止程序?
注意:上面的程序只是示例代码,用于解释我正在尝试做的事情。
如果同时包含 <thread>
和 <chrono>
,您可以调用
std::this_thread::sleep_for(std::chrono::seconds(1));
使当前线程休眠(暂停执行)一秒钟。
std::chrono 中预定义了很多时间步长,因此如果您想要更细粒度,可以调用其中之一。函数调用中的1
指定秒数。
但是,如果要使用上述语法,则不应使用调用退出。相反,在 try
块内使用异常并使用 catch
块捕获这些异常。您可以在 c++ here and here.
try-catch
块的更多信息
您可以从 std::cin
缓冲区中删除所有字符,然后调用 cin.get();
,并且仅在调用 return
之后(优于 std::exit
,因为后者不执行堆栈展开并且不为具有自动存储持续时间的对象调用析构函数)。
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;
相关:
这将阻止您的 dos window 关闭。
system("PAUSE") ;
将其添加到 return 语句之前。 您还可以使用 getch() 来阻止您的 dos window 被终止。