除了系统("pause")之外,是否有其他选项可以保持可执行文件打开?

Is there an option besides system("pause") for keeping an executable open?

本文关键字:选项 可执行文件 其他 系统 pause 是否 之外      更新时间:2023-10-16

我正在尝试从理解C++运行Caesar程序,一旦调试,它就不会保持打开状态。怎么办?

我使用系统("暂停"(无济于事。我也尝试过getchar((,它在其他应用程序中有效,但不适用于此可执行文件。

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
/** 
Encrypts a stream using the Caesar cipher
@param in- the stream to read from
@param out- the stream to write to 
@param k- the encryption key
*/
void encrypt_file(ifstream& in, ofstream& out, int k)
{
char ch;
while (in.get(ch))
{
out.put(ch + k);
}
}
int main(int argc, char* argv[])
{
int key = 3;
int file_count = 0; // The number of files specified
ifstream in_file;
ofstream out_file;
for (int i = 1; i < argc; i++) //Process all command-line arguments
{
string arg = argv[i]; // The currently processed argument
if (arg == "-d") // The decryption option
{
key = -3;
}
else // It is a file name
{
file_count++;
if (file_count == 1) // The first file name
{
in_file.open(arg.c_str());
if (in_file.fail()) // Exit the program if opening failed
{
cout << "Error opening input file " << arg << endl;
return 1;
}
}
}
}
if (file_count != 2) // Exit if the user didn't specify two files
{
cout << "Usage: " << argv[0] << " [-d] infile outfile" << endl;
return 1;
}
encrypt_file(in_file, out_file, key);
getchar();
//system("pause");
return 0;
}

预期结果是应用程序在解密代码时保持打开状态。

你实际上并没有将流指向任何地方。据我所知,ofstream将缓冲输入,直到您将其指向某个地方(免责声明,我可能是错的(。

无论如何,由于您没有为out_file打开任何内容,因此它不会写入您想要的任何文件。因此,看起来您的程序没有按照您想要的方式进行,只是返回。

您可以尝试使用系统("暂停/nul"(; 我在 VS 中制作 prograns 时使用,因为它们不会保持打开状态,但我只将它们放在返回 0 之前; 所以它们在我按下按钮后关闭,但我认为它在任何地方都有效,试一试。

相关文章: