如何在不必每次复制和粘贴代码的情况下选择执行多个数学问题?

时间:2017-03-03 23:36:08

标签: c++

我的代码允许用户输入一些数字或从文档中读取它们。我如何允许用户从数学问题中选择要对这些数字执行而不需要在我的主要代码中使用一堆代码。 到目前为止,这是我的代码:

#include <iostream>
#include <cmath>
#include <vector>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    //ask for file input or manual input
    cout << "Press 1 to enter numbers or 2 to read them from a list." << "\n";
    int choice;
    cin >> choice;

    if (choice == 1)
    {
        int numberswanted;
        cout << "How many numbers would you like to enter?" << "\n";
        cin >> numberswanted;

        vector<double> list;
        for (int i = 0; i < numberswanted; i++)
        {
            cout << "Enter your numbers: " << "\n";
            double x;
            cin >> x;
            list.push_back(x);
        }

    }
    else if (choice == 2)
    {
        ifstream doc;
        float output;
        doc.open("input.txt");
        while (!doc.eof())
        {
            vector<double> list;
            double x;
            doc >> x;
            list.push_back(x);
        }
        doc.close();

    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

可能你可以尝试这样的事情:

int main() { cout << "Press 1 to enter numbers or 2 to read them from a list." << "\n";
int choice;
cin >> choice;

if (choice == 1)
{
    choice1();

}
else if (choice == 2)
{
    choice2();

}
return 0;}
choice1包含int [...] list.push_back(x);}

等...