2012-02-21 100 views
0

我有一個叫做char * panimal_name的指針。這個指針只能輸入20個字符,如果用戶輸入更多,它必須要求用戶重新輸入。驗證char *取自std :: cin的長度

我試過在流中的字符計數,也使用strlen(),但我仍然有問題。

cout << "Enter Animal Name: "; 
cin.ignore(); 
cin.getline(panimal_name, 20); 

任何幫助,將不勝感激。

編輯:嗯,我只希望它從用戶最多隻需要20個字符。如果超過20,則應該要求用戶重新輸入有效的輸入。然而,在這個設置中,它現在爲我的下一個輸入弄虛作亂。我使用這個的原因,而不是std::string,因爲我現在正在學習指針。

P.S.我知道在這種情況下,字符串可能會更好,以便於使用。

+2

您遇到了什麼問題? – theglauber 2012-02-21 17:16:37

+3

你有沒有任何理由不使用字符串? – DumbCoder 2012-02-21 17:18:14

+1

@DumbCoder:由於某些原因,學校和大學絕對不希望學生使用字符串數據類型。他們吟唱「char *」的口頭禪。 (另外,幾乎從未提及STL的任何部分) – 2012-02-21 17:20:03

回答

0

爲用戶輸入使用較大的緩衝區並檢查緩衝區的最後一個元素。

1

您可以使用C++的方法..

std::string somestring; 

std::cout << "Enter Animal Name: "; 
std::cin >> somestring; 

printf("someString = %s, and its length is %lu", somestring.c_str(), strlen(somestring.c_str())); 

你也可以用多個C++方法

std::string somestring; 

std::cout << "Enter Animal Name: "; 
std::cin >> somestring; 

std::cout << "animal is: "<< somestring << "and is of length: " << somestring.length(); 

我想你可以做一些與CIN一個字符串流來避開這一CIN的方式exctract作品。

+0

請您對最後一句話進行擴充嗎? cin如何從其他流中提取不同的信息? – 2012-02-21 17:42:28

+0

有點諷刺意味,你如何說「使用C++方法」,然後使用'printf'。 ;-) – 2012-02-21 18:32:02

+0

konrad ...是的,我可以只刪除那部分..搶,讓我嘗試一些代碼的東西...正常的提取行爲只能基本上到下一個空間...你可以做到遞歸的同時沒有最後... – 2012-02-21 20:32:54

1

根據MSDN:

如果函數不提取元素或_COUNT - 1個元素,它調用 setstate這(failbit)...

你可以檢查該failbit看如果用戶輸入的數據超過緩衝區允許的數量?

1

考慮下面的程序:

#include <iostream> 
#include <string> 
#include <limits> 

// The easy way 
std::string f1() { 
    std::string result; 
    do { 
    std::cout << "Enter Animal Name: "; 
    std::getline(std::cin, result); 
    } while(result.size() == 0 || result.size() > 20); 
    return result; 
} 

// The hard way 
void f2(char *panimal_name) { 
    while(1) { 
    std::cout << "Enter Animal Name: "; 
    std::cin.getline(panimal_name, 20); 
    // getline can fail it is reaches EOF. Not much to do now but give up 
    if(std::cin.eof()) 
     return; 
    // If getline succeeds, then we can return 
    if(std::cin) 
     return; 
    // Otherwise, getline found too many chars before '\n'. Try again, 
    // but we have to clear the errors first. 
    std::cin.clear(); 
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
    } 
} 

int main() { 
    std::cout << "The easy way\n"; 
    std::cout << f1() << "\n\n"; 

    std::cout << "The hard way\n"; 
    char animal_name[20]; 
    f2(animal_name); 
    std::cout << animal_name << "\n"; 
}