C++ 限制一个集合内的字符串长度?
我必须编写一个程序,允许用户输入最多20个名称,每个名称最多40个字符 当我编写代码时,没有试图以任何方式限制字符串长度,它是有效的。但是,当我试图用if/else语句限制字符串长度时,它不起作用。我对C++很陌生,所以它真是一个黑暗的例子。我做错了什么C++ 限制一个集合内的字符串长度?,c++,set,string-length,C++,Set,String Length,我必须编写一个程序,允许用户输入最多20个名称,每个名称最多40个字符 当我编写代码时,没有试图以任何方式限制字符串长度,它是有效的。但是,当我试图用if/else语句限制字符串长度时,它不起作用。我对C++很陌生,所以它真是一个黑暗的例子。我做错了什么 #include <iostream> #include <string> #include <set> #include <algorithm> using namespace std; v
#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;
}
编辑的代码:
#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;
}
}
#包括
#包括
#包括
#包括
使用名称空间std;
无效打印(常量字符串和名称){
cout您似乎说过,如果将条件更改为name.size()>=40,则仅在字符串大于40且不小于40时运行代码
在else break中,crr和th语句都应该在{}内
if (name.size() <= 40) {
ListOfNames.insert(name);
}
else
{
cerr << "You entered more than 40 characters. Please try again.";
break;
}
if(name.size()编写一个单独的函数来获取和验证输入。在该函数中,检查输入长度是否少于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;
}
std::string get\u limited\u string(std::string提示符,int max=40){
std::字符串输入;
做{
标准::cout=最大值);
返回输入;
}
当我这样做时,它只允许我输入1个名称,而不是全部20个名称。例如:input:1.Max Output:Maxyou忘记关闭For循环的括号。在关闭else之后关闭For循环,它应该可以从收集20个输入字符串的循环中调用它。
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;
}