2013-04-21 510 views
2

我想要它,以便當用戶輸入超過5個字符時,會發生一些事情,而不是僅僅跳過其餘部分。如何限制C++中用戶輸入的最大字符數?

在此代碼中,如果您鍵入的字符數超過5個,則只會顯示前5個字符。 我想在這裏放一個「if」語句,如果用戶輸入5個以上的字符,它會顯示一個錯誤或其他內容,而不僅僅顯示前5個字符。

#include <iostream> 
#include <iomanip> 

int main() 
{ 
using namespace std; 
string nationname; 
int maxchar = 5; 
cout << "What is the name of your nation?\n"; 

cin >> setw(maxchar) >> nationname; 

cout << "The name of your nation is " << nationname; 
cin.ignore(); 

return 0; 
} 

謝謝!

回答

3

你可以先完整閱讀的字符串,然後驗證它:

int main() 
{ 
    using namespace std; 

    const int maxchar = 5; 
    string nationname; 

    cout << "What is the name of your nation?" << endl; 

    cin >> nationname; 

    if (nationname.size() > maxchar) 
    { 
     err << "The input is too long." << endl; 
     return 1; 
    } 

    // ... 
} 

順便說一句,你應該使用std::endl您提示,而不只是\n;您希望在開始等待用戶輸入之前確保將提示刷新到屏幕上。 (編輯:作爲洛基阿斯塔在評論中指出,這部分實際上不是必要的)

+0

謝謝!你知道如何在它說錯誤之後將它循環回「cout」嗎? – Leroterr1 2013-04-21 18:58:49

+0

'do {cin >> nationname; if(nationname.size()> maxchar)/ * output * /} while(nationname.size()> maxchar);' – Zaiborg 2013-04-21 19:03:01

+0

謝謝!詹姆斯德林和Zaiborg。 – Leroterr1 2013-04-21 19:21:07

0

**

#include <iostream> 
#include <iomanip> 
#include<string> 
#include <conio.h> 
int main() { 
    using namespace std; 
    const int maxchar = 6; 
    string nationname; 
    cout << "What is the name of your nation?" << endl; 
    getline(cin, nationname); 
    if (nationname.size() > maxchar) 
    { 
     cout << "The input is too Short." << endl; 
    } getch(); 
    return 0; 
} 

**

您可以使用此代碼。這是完美的,沒有任何錯誤。你也可以將其轉換成最小字符,進行少許更改。