gpt4 book ai didi

c++ - 限制一组内的字符串长度?

转载 作者:行者123 更新时间:2023-11-30 03:42:07 24 4
gpt4 key购买 nike

我必须编写一个程序,允许用户输入最多 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;
}
}

最佳答案

你好像说只有当字符串大于 40 且不小于 40 时才运行代码

关于c++ - 限制一组内的字符串长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36969845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com