我必须编写一个程序,允许用户输入最多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;
}
}
答案 0 :(得分:1)
如果字符串大于40且不小于40
,您似乎只说运行代码答案 1 :(得分:1)
编写一个单独的函数来获取并验证输入。在该函数中,检查输入是否少于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;
}
答案 2 :(得分:0)
inside如果将条件更改为name.size()&gt; = 40
并且in cr在crr之后中断并且两个语句都应该在{}
之内if (name.size() <= 40) {
ListOfNames.insert(name);
}
else
{
cerr << "You entered more than 40 characters. Please try again.";
break;
}