【问题标题】:Extract an specific count of chars with cin.get and make sure is correct使用 cin.get 提取特定数量的字符并确保正确
【发布时间】:2013-12-07 10:38:36
【问题描述】:

我想从输入中提取 6 个字符(包括“\n”)到一个数组,并通过在数组中的特定位置获取换行符来确保输入正确。这就是我所做的,但我无法修复它。如果用户输入超过 5 个字符,则循环重复,但剩余字符仍在流中。使用 cin.ignore('\n') 我得到一个无限循环,流中没有字符。

do
{
    cout << "Please log in: \n";
    cin.get(username, 6);
    cin.ignore('\n'); 
    if (username[5] != '\n')
        cout << "\nYour username should be 5 digits!\n\n";
} while (username[5] != '\n');

【问题讨论】:

  • 我不明白,你想得到包括 "\n" 在内的 6 个字符,但你使用的是 cin.ignore('\n') ??
  • 如果你使用 C++ 为什么不使用 std::string 而不是 char[] ?

标签: c++ arrays getline


【解决方案1】:

除非您真的想逐个字符输入,否则请考虑使用字符串并然后确保您的输入有效。这将大大简化代码并使其更易于维护:

string username;

if (cin >> username) {
    if (username.length() != 5) {
        // report bad input
    }
}

【讨论】:

    【解决方案2】:

    使用字符串可以更轻松地完成您想要做的事情,就像这样:

    string username = "";
    do
    {
        cout << "Please log in: \n";
        cin>>username ; 
        if (username.length() != 5)
            cout << "\nYour username should be 5 digits!\n\n";
    } while (username.length() != 5);
    

    但不要忘记将#include&lt;string&gt; 添加到您的代码中

    【讨论】:

      猜你喜欢
      • 2021-11-09
      • 2020-09-09
      • 1970-01-01
      • 2011-04-18
      • 2018-10-10
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多