繁体   English   中英

如何使用输入终止 C++ 中的程序?

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

我试图用这个程序完成的是让用户输入尽可能多的数字到 vecor 中。 用户完成后,我希望用户输入“否”一词。 用户输入“no”这个词后,将计算向量的大小、最大值、最小值和平均值。 我的问题是我目前的程序设置为如果用户输入数字“0”,程序将终止。 问题在于数字输入是在向量大小和最小值计算中计算出来的。 无论如何,用户可以输入字符串 vaule "no" 并终止程序而不是输入数字零吗?

谢谢 !

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;
    }

} 在此处输入代码

您可以将每一行读取为std::string并检查它是否为no 如果不是,请将其转换为double std::stod (例如使用std::stod )并保存。

例子:

#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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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