2012-02-21 101 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"; 
}