2012-11-30 80 views
1

如果用户输入整数而不是字符或字符串,我需要检查我的程序。 字符并没有那么糟糕,因为它实际上是一个整数,但如果用户输入一个字符序列,那么它只是疯了。如何检查用户是否输入整数

我做了这个功能

int* ask_lung(int* lung) 
{ 
int tmp; // length of a word 

cout << "Inserisci la lunghezza della parola da indovinare: "; 
cin >> tmp; 

if(cin) 
{ 
    // Se i è uguale a o minore di 0 allora ritorna all'inizio 

    if(tmp <= 0) 
    { 
     cout << endl << "\tNon puoi inserire 0." << endl << endl; 
     ask_lung(lung); 
    } 
    else 
    { 
        // the error is about here, when it reaches this part of the code it keeps showing the first line "Inserisci la lunghezza della parola da indovinare: " 
     *lung = tmp; 
    } 
} 
else ask_lung(lung); 

return lung; 
} 
+0

这是做什么/应该做什么? – asheeshr

+0

while(!(cin >> myInt)){std :: cout <<“您的输入不是int”<< std :: endl} 或者我明白错了什么? – demonking

+0

如果tmp <= 0或一个字符或字符序列它应该打印一个错误,并再次要求输入 – DomeWTF

回答

2

在字符的字符串的情况下,你的流包含大量的无效字符,您需要在这些字符流刷新到一个新的状态。而不是递归地做,最好在循环中做到这一点。这对你来说是合理的。

while(true) 
{ 
    cout << "Please Enter an Integer" << endl ; 
    if (cin >> temp) //true if a leading integer has entered the stream 
    break ; 
    else 
    { 
    cout << "Invalid Input" << endl ; 
    cin.clear() ; 
    cin.ignore(std::numeric_limits<streamsize> :: max(), '\n') ; 
    } 
} 
+0

谢谢,就像我以为我不得不清理流,现在它工作得很好。 – DomeWTF

+0

can you explain me please cin.ignore(std :: numeric_limits :: max(),'\ n'); ? – DomeWTF

+0

我们是否需要处理'12x '的情况,其中第一部分是一个整数,然后有一些垃圾在线? –

-2

输入处理正确,问题是您要返回一个指向局部变量的指针。该变量位于堆栈上,一旦函数返回,它将被释放。相反,你应该只返回整数本身,而不是指向它的指针。

编辑:我看到实际上你没有返回一个指向整数的指针,而是指向指针指向的整数。不过,最好只返回整数本身。

+0

'* lung = tmp'改变'lung'指向的值,而不是其地址。输入处理不正确。 –

1

您可以使用std::all_ofstd::isdigit沿:

std::string input; 
std::cin >> input; 

if (std::all_of(input.begin(), input.end(), std::isdigit)) 
{ 
    //input is integer 
} 

或者,如果你想测试,也希望整数,那么最好是使用inputint,其他答案的建议。如果您已经(读取)了字符串,您可以考虑使用std::stoi。请注意,std::stoi在发生错误时会引发异常。

+0

与'operator >> int'不同的语义。您的版本检查是否所有到下一个空格的字符都是数字。这里的问题可能包含一个输入(即年龄跟名称)。 –

+0

@LokiAstari:'1e3'不是一个整数。 – Nawaz

+0

Opps。固定。 :-) –