【问题标题】:Limit string length within a set?限制集合内的字符串长度?
【发布时间】:2016-08-26 11:23:37
【问题描述】:

我必须编写一个程序,允许用户输入最多 20 个名称每个名称最多 40 个字符

当我编写代码而不试图以任何方式限制字符串长度时,它可以工作。但是当我尝试使用 if/else 语句限制字符串长度时,它不起作用。我对 C++ 很陌生,所以它真的是在黑暗中拍摄。我做错了什么?

#include <iostream>
#include <string>
#include <set>
#include <algorithm>

using namespace std;

void print(const string& name) {
    cout << name << endl;
}

int main() {
    set<string> ListOfNames;
    cout << "Please enter up to 20 names of up to 40 characters each below:     " << endl;
for (int i = 1; i <= 20; ++i) {
    string name;
    cout << i << ". ";
    getline(cin, name);
    if (name.size() >= 40) {
        ListOfNames.insert(name);
    }
    else break;
    cerr << "You entered more than 40 characters. Please try again.";
}

for_each(ListOfNames.begin(), ListOfNames.end(), &print);
return 0;

}

输出:

1. (user inputs name here)
press any key to continue...

编辑代码

#include <iostream>
#include <string>
#include <set>
#include <algorithm>

using namespace std;

void print(const string& name) {
    cout << name << endl;
}

int main() {
    set<string> ListOfNames;
    cout << "Please enter up to 20 names of up to 40 characters each below:         " << endl;
for (int i = 1; i <= 20; ++i) {
    string name;
    cout << i << ". ";
    getline(cin, name);
    if (name.size() <= 40) {
        ListOfNames.insert(name);
    }
    else
    {
        cerr << "You entered more than 40 characters. Please try again.";
        break;
    }

    for_each(ListOfNames.begin(), ListOfNames.end(), &print);
    return 0;
    }
}

【问题讨论】:

    标签: c++ set string-length


    【解决方案1】:

    您似乎说仅当字符串大于 40 而不是小于 40 时才运行代码

    【讨论】:

      【解决方案2】:

      编写一个单独的函数来获取和验证输入。在该函数中,检查输入是否少于 40 个字符,如果不是,则拒绝接受:

      std::string get_limited_string(std::string prompt, int max = 40) {
          std::string input;
          do {
              std::cout << prompt;
              std::getline(std::cin, input);
          } while (input.size() >= max);
          return input;
      }
      

      【讨论】:

      • 从收集 20 个输入字符串的循环中调用它。
      【解决方案3】:

      inside if 将条件改为 name.size() >= 40

      and in else break 在 crr 之后,两个语句都应该在 {}

      if (name.size() <= 40) {
          ListOfNames.insert(name);
      }
      else
      {
          cerr << "You entered more than 40 characters. Please try again.";
          break;
      }
      

      【讨论】:

      • 当我这样做时,它只允许我输入 1 个名称,而不是全部 20 个。例如:输入:1。最大输出:最大
      • 您忘记关闭 for 循环的括号。关闭 else 后关闭 for 循环,它应该可以正常工作
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多