【问题标题】:C++ Prevent CMD Commands being usedC++ 防止使用 CMD 命令
【发布时间】:2015-11-18 13:34:15
【问题描述】:

为(之前的?)措辞不当的问题道歉

我试图阻止使用 CMD 命令。特别是 F6 是我无法解决的唯一按钮。输入 F6 关闭程序或循环 userName() 函数。

由于 F6 或 Ctr+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);
}

【问题讨论】:

  • cin &gt;&gt; 没有“无限循环”——没有循环语句。您的其余代码(包含循环的部分)是什么样的?
  • 你还记得clear直播状态吗?
  • 使用 cin、cout 和 string,您已经在使用标准库。没有标准库真的很难写,除非你先重写一大块标准库。
  • cin 已经是标准库的一部分

标签: c++ error-handling cmd command


【解决方案1】:

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

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

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

您当然可以采取您喜欢的任何其他操作,而不是致电exit(1)

【讨论】:

  • 非常感谢,这正是我想要的。我没有意识到可以说 !cin 或 if("Actually we didn't get any input")
  • 只需要添加一个 cin.clear();在调用 userName() 之前;功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
相关资源
最近更新 更多