c++禁止使用CMD命令

C++ Prevent CMD Commands being used

本文关键字:CMD 命令 禁止 c++      更新时间:2023-10-16

为(上一个?)措辞不恰当的问题道歉

我试图阻止CMD命令被使用。特别是F6是我唯一不能工作的按钮。输入F6将关闭程序或循环userName()函数。

由于F6或ctrl +Z是直接进入循环的命令。它导致我的程序无法预测。在一台机器上它无限循环,在我自己的机器上它只是关闭窗口

我的评估的一部分,从我开始就把我逼疯了。我的许多同龄人也有问题,但这是一个直接的要求,如果他能让我们的程序崩溃,那就是一个立即的"失败"。这就是为什么我一直坚持只允许以下定义的字符:

 size_t found = user.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");

按要求也有足够的程序来重复这个问题:

#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <string>
#include <istream>
#include <cstddef>   
string name = { "" };
int menu();
int errorChecking(string user);
int userName();
    int main() 
{
    cout  << "-------------------- Welcome! --------------------"  << endl << endl;
    userName();
}
int errorChecking(string user)
{
    size_t found = user.find_first_not_of("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890");
    if (found != string::npos)
    {
        cout << name[found] << " is not an acceptable character." << 'n';
        cout << "Enter a valid name ";
        cout << endl << endl;
        userName();
    }
    return(0);
}
int userName()
{
    cout << "Enter your name: ";
    std::getline(cin, name);
    //if (name == "→") { cin.clear(); userName(); }
    errorChecking(name);
    return(0);
}

问题是CtrlZ在Windows终端提示符下表示"文件结束"。当cin遇到文件结束时,流进入错误状态,并且对std::getline(cin, name)的进一步调用实际上不会等待用户键入任何输入。

你需要做的是适当地处理流错误状态。一种方法是:

cout << "Enter your name: ";
std::getline(cin, name);
if (!cin) {
    cerr << "Unexpected end of file encountered on cinn";
    exit(1);
}
errorChecking(name);

你当然可以采取任何你喜欢的行动,而不是调用exit(1)