2016-04-25 65 views
-2

的陣列工作當我嘗試從用戶的用戶名來獲得,我做了以下內容:CIN是不是字符

#include <iostream> 

using namespace std; 
void main(){ 
char *usrn=new char[20]; //Max username length of 20 alfanumeric characters 
    std::string usrn_str; 
     while (true){ 
      std::cout << "Enter the username(3-20 characters): "; 
      cin.clear(); 
      cin.ignore(); 
      std::cin.getline(usrn,22); 
      usrn_str=usrn; 
      if ((usrn_str.length())<3){ 
       cout << "Introduced username too short!" << endl; 
      } 
      else if ((usrn_str.length())>=21){ 
       cout << "Introduced username too long!" << endl; 
      } 
      else { 
       cout << usrn_str.c_str() ; 
      } 
     } 
} 

不管怎麼說,引入時,一個更大的用戶名超過了允許一個,即25,這表明我引入的用戶名太長的消息,但在下一個循環中,我不能再輸入用戶名,因爲這需要輸入上述示例中的最後5個字符。總結一下,如果我輸入一個長度爲30的用戶名,它會丟棄前20個用戶名,並將最後10個用戶名作爲用戶名,當我想要詢問用戶名時,我會得到一個長度爲3-20的用戶名。

我該如何執行它?任何幫助表示讚賞。

+0

嘗試'的std :: cin.ignore(256, '\ n')' – ArchbishopOfBanterbury

+3

使用['的std :: string'](http://en.cppreference.com/w/cpp/string/basic_string),讀入整個用戶名,然後檢查大小。如果它太大,請重複。 – NathanOliver

+0

爲什麼你根本用這個指針來表示char?使用'std :: string',你會沒事的。 – ForceBru

回答

1

使用std::getline()來讀取整個用戶輸入(用戶輸入是基於行的)。然後對輸入行進行驗證檢查。

bool  finished = false; 
std::string name; 
do 
{ 
    if (std::getline(std::cin, name)) 
    { 
      // You have successfully read one line of user input. 
      // User input is line based so this is usually the answer to 
      // one question. 
      // 
      // Do your validation checks here. 
      // If the user entered data that checks out then set 
      // finished to true. 
    } 
    else 
    { 
      // There was a problem reading the line. 
      // You need to reset the stream to a good state 
      // before proceeding or exit the application. 
    } 
} 
while(!finished);