2013-04-20 44 views
0

如何使用C++检查非数字输入?我正在使用cin读取float值,并且我想检查是否通过stdin输入非数字输入。我试图用%d指示符来使用scanf,但我的输出已损坏。当使用cin时,我得到正确的格式,但是当输入字符串如“dsffsw”时,我得到一个无限循环。 评论的代码是我试图捕获浮动,并将其转换为字符串,并检查它是否是一个有效的浮动,但检查总是出现错误。检查C++程序中的非数字输入

我尝试过使用其他方法在留言板上找到,但他们想在C中使用scanf而不是在C++中使用cin。你如何在C++中做到这一点?或者在C中如果不可行。

while (!flag) { 
     cout << "Enter amount:" << endl; 
     cin >> amount; 


    cout << "BEGIN The amount you entered is: " << strtod(&end,&pend) << endl; 

     //if (!strtod(((const char *)&amount), NULL)) { 
     // cout << "This is not a float!" << endl; 
     // cout << "i = " << strtod(((const char *)&amount), NULL) << endl; 
     // //amount = 0.0; 
     //} 

     change = (int) ceil(amount * 100); 

     cout << "change = " << change << endl; 

     cout << "100s= " << change/100 << endl; 
     change %= 100; 
     cout << "25s= " << change/25 << endl; 
     change %= 25; 
     cout << "10s= " << change/10 << endl; 
     change %= 10; 
     cout << "5s= " << change/5 << endl; 
     change %= 5; 
     cout << "1s= " << change << endl; 
     cout << "END The amount you entered is: " << amount << endl; 
} 
return 0; 

}

+0

你错过了几这段代码中的变量声明。 – WhozCraig 2013-04-20 05:57:00

+0

http://www.parashift.com/c++-faq/istream-and-ignore.html – chris 2013-04-20 06:00:34

+0

大多数情况下,在C++中,您的读取语句需要处于while循环的条件。那么失败将导致while循环终止而不是你的程序。 – 7stud 2013-04-20 06:11:46

回答

1
int amount; 

cout << "Enter amount:" << endl; 

while(!(cin >> amount)) { 
    string garbage; 
    cin.clear(); 
    getline(cin,garbage); 
    cout << "Invalid amount. " 
     << "Enter Numeric value for amount:" << endl; 
} 
+0

我喜欢'getline(cin,garbage)',它比cin.ignore(std :: numeric_limits :: max(),'\ n')'更加明显。但是垃圾的声明应该在while循环中移动。 – john 2013-04-20 06:16:58

+0

@john你好点。将解决。 – stardust 2013-04-20 06:17:56

0

试试这个方法来检查的有效性:

float amount; 

if (cin >> amount) 
{ 
    cout << "Ok" << endl; 
} 
else 
{ 
    cout << "Invalid" << endl; 
} 
0

我想,你的任务涉及所谓防御式编程,它单曲的想法之一是为了防止你描述的情况(功能需要一种类型,用户输入另一种类型)。

我给你来判断使用方法,返回流状态,这是good()
所以我认为这将是这个样子的输入是否正确:

int amount = 0; 
while (cin.good()) { 
     cout << "Enter amount:" << endl; 
     cin >> amount;