如何在 c++ 中使用空格实现 Cin<<

  • 本文关键字:空格 实现 Cin c++ c++ cin
  • 更新时间 :
  • 英文 :


>有谁知道控制台应用程序在一行上具有 3 个用户输入的最佳方法。例如:

(命令"搜索"时间)

像这样的东西将允许在一行上写三个字符串:

std::string line;
std::getline(std::cin, line);
std::istringstream iss(line);
std::string command, param1, param2;
if (!(iss >> command >> param1 >> param2)) {
    std::cout << "Missing some input.n";
} else if (std::cin >> std::ws && std::cin.peek() != EOF) }
    std::cout << "Too many parameters.n";
} else {
    std::cout << "Ok.n";
}

这是另一种方法: 重载operator>>以使其与元组一起使用

#include <iostream>
#include <tuple>
template<typename T>
T read(std::istream& is)
{
    T value;
    is >> value;
    return value;
}
template<typename... Ts>
std::istream& operator>>(std::istream& is , std::tuple<Ts...>& tuple)
{
    tuple = std::make_tuple( read<Ts>(is)... );
    return is;
}

其使用示例可以是:

int main()
{
    std::tuple<int,int> tuple;
    std::cin >> tuple;
}

这是 ideone 的一个运行示例。

最新更新