0

我正在编写一个 c++ 程序来安装我放在几台计算机上的某些程序。我在代码中放置了一个部分,允许用户选择他们想要的安装。我对 C++ 很生疏,所以我无法接受用户输入。我愿意接受有关更好方法的建议,我相信有几个。

    int allOrSelect;

std::cout << "Press 1 if you want all software, press 2 if you want to select";
std::cin >> allOrSelect;

if(allOrSelect == 1)
{
    std::cout<< "all software installing ..." <<std::endl;
}

if(allOrSelect == 2)
{
    std::cout << "Please select from the following list";
    std::cout << "software 1";
    std::cout << "software 2";
    std::cout << "software 3";
    std::cout << "software 4";
    std::cout << "Type the appropriate numbers separated by space or comma";
//this is where trouble starts
//I've tried a few different ways to take the user input
//i tried using vector array, but never got it working, but i figured there had to 
//be a simpler way.  also tried variations of cin.whatever
}

如果您需要更多信息,请告诉我,并提前致谢。

4

1 回答 1

0

假设用户输入是逗号分隔的值(例如,“1, 2, 3”),输入应该使用std::istringstream类进行标记。std::set用于防止重复值。

请注意,代码实际上并没有实现输入验证。

#include <set>
#include <iostream>
#include <sstream>

// Read the string representation:
// "1, 2, 3"
std::string input;
std::getline(std::cin, input);

// Convert to set of integers.
std::set<int> selection;
std::istringstream ss(input);
std::string softItem;

while (std::getline(ss, softItem, ','))
{
    std::stringstream stm;
    stm.str(softItem);

    int i;
    if (!(stm >> i))
    {
        // TODO: handle input error!
        std::cout << "Input error!" << std::endl;
        break;
    }
    selection.insert(i);
}

// Logic:
// The selection set contains the user selection.
于 2012-08-02T19:02:58.727 回答