【问题标题】:Installing multiple programs c++ taking user input through array or another way安装多个程序 c++ 通过数组或其他方式获取用户输入
【发布时间】:2012-08-02 18:22:18
【问题描述】:

我正在编写一个 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
}

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

【问题讨论】:

  • 查看std::cin 的输入和std::endl 以在每个文本字符串的末尾输出一个换行符。

标签: c++ arrays input vector


【解决方案1】:

假设用户输入是逗号分隔的值(例如,“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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-23
    • 2011-03-03
    • 1970-01-01
    • 2011-07-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多