2016-05-01 15 views
1

私はユーザが名前を入力することができるプログラムを書く必要がありますそれぞれ最大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; 
    } 
} 

答えて

0

inside条件をname.size()> = 40に変更する場合

CRR後

、他休憩中と目の両方のステートメントは、{}

if (name.size() <= 40) { 
    ListOfNames.insert(name); 
} 
else 
{ 
    cerr << "You entered more than 40 characters. Please try again."; 
    break; 
} 
+0

これを実行すると、すべての名前ではなく1つの名前を入力できます。 例: 入力:1.最大 出力:最大 –

+0

編集したコードを投稿してください。 – Reshad

+0

最後に新しいコードを編集して追加しました。 –

1

あなたは、文字列が40

以上で40以上である場合にのみコードを実行するために言ったように思え
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; 
} 
+0

私のコードでこの関数をどこで呼び出すのですか? –

+0

20の入力文字列を収集するループから呼び出します。 –

関連する問題