-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的用戶名。
我該如何執行它?任何幫助表示讚賞。
嘗試'的std :: cin.ignore(256, '\ n')' – ArchbishopOfBanterbury
使用['的std :: string'](http://en.cppreference.com/w/cpp/string/basic_string),讀入整個用戶名,然後檢查大小。如果它太大,請重複。 – NathanOliver
爲什麼你根本用這個指針來表示char?使用'std :: string',你會沒事的。 – ForceBru