简体   繁体   中英

How to use an input to terminate a program in c++?

What I am trying to accomplish with this program is for a user to enter as many numbers as they would like into a vecor. After the user is finished I would like the user to enter the word "no". After the user inputs the word "no" the size of the vector, max vaule, min vaule and mean value will be calculated. My problem is I currently have my program set up to were if a user enters the number "0" the program will then terminate. The issue with this is that number input gets calculated in the vector size and minimum vaule calculation. Is there anyway where a user can enter the string vaule "no" and terminate the program instead entering the number zero?

Thanks !

enter code here

#include <iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<numeric>

using namespace std;

int main(){

    std::vector<double> numbers;
    std::vector<double>::iterator it;

    double number;
    cout<<"Hello! Enter as many numbers as you would like! \n When you are finished enter 0"<<endl;

    while (cin>>number){

        numbers.push_back(number);{

            while(number==0){
                for (it=numbers.begin(); it !=numbers.end(); it++)
                cout << *it<< " ";
                cout << endl;

                cout<< "The total size of the Numbers vector is: "<<numbers.size();

                double max = *max_element(numbers.begin(), numbers.end());
                cout << "\nMax Value: "<<max<<endl;

                double min = *min_element(numbers.begin(), numbers.end());
                cout << "Min Value: "<<min<<endl;

                double mean = accumulate(numbers.begin(), numbers.end(), 0) / numbers.size();
                cout <<"Mean Value: "<<mean<<endl;

                return 0;
            }

        }
        cout<<endl;
    }

} enter code here

You could read each line as a std::string and check if it's no . If it's not, convert it to a double (using std::stod for example) and save it.

Example:

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<double> numbers;
    std::string line;
    while(std::getline(std::cin, line)) {
        if(line == "no") break;
        try {
            numbers.push_back(std::stod(line));
        } catch(const std::exception& ex) {
            // converting to double failed
            std::cout << ex.what() << '\n';
        }
    }
    // do your calculations
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM