【发布时间】: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