私はユーザが名前を入力することができるプログラムを書く必要がありますそれぞれ最大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...
EDITED CODE:
#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;
}
}
これを実行すると、すべての名前ではなく1つの名前を入力できます。 例: 入力:1.最大 出力:最大 –
編集したコードを投稿してください。 – Reshad
最後に新しいコードを編集して追加しました。 –