如果输入的不是数字,则程序终止

时间:2019-07-11 17:05:01

标签: c++ c++11

我正在通过“编程:使用C ++的原理和实践”进行工作。而且我无法让我的程序接受双精度然后是字符串。输入字符串后,它将终止。

如果我输入任何数字(即100),则它会按预期工作,并输出迄今最小和最大的数字。

如果我输入100m,100 m,100,m,程序将输出迄今为止最小和最大的输出,但是我无法输出字符串单位“ m”。

我正在自学,因此,即使与该问题无关的任何输入,也将不胜感激。

谢谢

我已经尝试过val1击中enter然后输入字符串。 我已经尝试过https://github.com/bewuethr/stroustrup-ppp/blob/master/chapter04/chapter04_drill.cpp,但我什至无法让该程序在netBeans上运行 我添加了一个通用字符串“ unit”

#include "std_lib_facilities.h"

int main ()
{

    double val1 = 0; // initialized
    double val1_conv = 0; //intialized
    double smaller = INFINITY; // initialized
    double larger = -INFINITY; // initialized

    vector<double> compare; // empty vector of doubles


    string unit = "";  // Added this to see if it would allow a string, I've also tried removing the = "" 
    string meter = "m";
    string centi = "cm";
    string foot = "ft";
    string inch = "in";

    cout << "Please input a value follow by unit (ie cm,m, in,ft), us | to stop" << endl; // put into

    while (cin >> val1 >> unit)   // cin "get from"
    {
        compare.push_back(val1);

        if (unit == "m") // Just trying to get the program to accept a string after an double
        {
            cout << val1 << unit;
        }

        if (val1 < smaller)
        {
            smaller = val1; // assignment giving a variable a new value
            cout << val1 << " is the smallest so far \n";
            compare.push_back(smaller);
        }

        if (val1 > larger)
        {
            larger = val1;   // assignment giving a variable a new value
            cout << val1 << " is the largest so far \n";
            compare.push_back(larger);
        }

    }
    return 0; // The book doesn't have us adding this line to everything but I tried it.
}

就像我没有在val中添加任何字符串或单位一样

0 个答案:

没有答案