【问题标题】:How do you limit the maximum amount of characters in user input in C++?如何限制 C++ 中用户输入的最大字符数?
【发布时间】:2013-04-21 18:41:55
【问题描述】:

我想要这样当用户输入超过 5 个字符时,就会发生一些事情,而不是跳过其余的。

在此代码中,如果您输入超过 5 个字符,它将只显示前 5 个字符。 我想在这里放一个“if”语句,如果用户输入超过 5 个字符,它将显示错误或其他内容,而不仅仅是显示前 5 个字符。

#include <iostream>
#include <iomanip>

int main()
{
using namespace std;
string nationname;
int maxchar = 5;
cout << "What is the name of your nation?\n";

cin >> setw(maxchar) >> nationname;

cout << "The name of your nation is " << nationname;
cin.ignore();

return 0;
}

谢谢!

【问题讨论】:

    标签: c++ cin iomanip setw


    【解决方案1】:

    您可以先完整读取字符串,然后对其进行验证:

    int main()
    {
        using namespace std;
    
        const int maxchar = 5;
        string nationname;
    
        cout << "What is the name of your nation?" << endl;
    
        cin >> nationname;
    
        if (nationname.size() > maxchar)
        {
           err << "The input is too long." << endl;
           return 1;
        }
    
        // ...
    }
    

    顺便说一句,您应该在提示中使用std::endl 而不仅仅是\n;您要确保在开始等待用户输入之前将提示刷新到屏幕上。 (编辑:正如 Loki Astari 在 cmets 中指出的那样,这部分实际上并不是必需的。)

    【讨论】:

    • 谢谢!你知道如何在它说错误后将它循环回“cout”吗?
    • do{cin &gt;&gt; nationname; if(nationname.size() &gt; maxchar) /*output*/ }while( nationname.size() &gt; maxchar);
    • 谢谢! jamesdlin 和 Zaiborg。
    • 其实没有必要使用std::endl。标准流(std::cin 和 std::cout)是同步的,以便在检索用户输入之前刷新到 std::cout 的所有输出。
    【解决方案2】:

    **

    #include <iostream>
    #include <iomanip>
    #include<string>
    #include <conio.h>
    int main() {
        using namespace std;
        const int maxchar = 6;
        string nationname;
        cout << "What is the name of your nation?" << endl;
        getline(cin, nationname);
        if (nationname.size() > maxchar)
        {
           cout << "The input is too Short." << endl;
        }   getch(); 
        return 0; 
    }
    

    **

    您可以使用此代码。这是完美的工作,没有任何错误。您也可以将其转换为最小字符输入,只需进行少量更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-22
      • 1970-01-01
      • 2011-04-02
      相关资源
      最近更新 更多