【问题标题】:Check for non-numeric inputs in a C++ program检查 C++ 程序中的非数字输入
【发布时间】:2013-04-20 14:18:12
【问题描述】:

如何使用 C++ 检查非数字输入?我正在使用 cin 读取浮点值,并且我想检查是否通过标准输入输入了非数字输入。我曾尝试使用 %d 指示符来使用 scanf,但我的输出已损坏。使用 cin 时,我得到了正确的格式,但是当我输入诸如“dsffsw”之类的字符串时,我得到了一个无限循环。 注释代码是我尝试捕获浮点数,并将其类型转换为字符串,并检查它是否是有效的浮点数,但检查总是错误的。

我尝试使用在留言板上找到的其他方法,但他们想在 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;

}

【问题讨论】:

  • 您在这个 sn-p 中缺少一些变量声明。
  • 在 C++ 中的大多数情况下,您的读取语句需要处于 while 循环的条件中。然后失败将导致while循环而不是你的程序终止。

标签: c++ visual-studio-2010


【解决方案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;
}

【讨论】:

  • 我喜欢getline(cin, garbage),比满口的cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(), '\n')要明显一点。然而,垃圾声明应该移到 while 循环内。
【解决方案2】:

我认为您的任务与所谓的防御性编程有关,其中一个想法是防止出现您所描述的情况(函数需要一种类型而用户输入另一种)。

我提供给你使用返回流状态的方法来判断输入是否正确,即good(),
所以我认为它看起来像这样:

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

【讨论】:

    猜你喜欢
    • 2022-01-23
    • 2012-02-22
    • 2020-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    相关资源
    最近更新 更多