c++ - 如何接受可变数量的输入?

标签 c++

假设我有一个包含 5 次迭代的 for 循环。 每次循环,我都需要输入 string int intstring int int int。 也就是说,在每次迭代中,程序都会要求一个字符串和 2 个整数的组合,或者一个字符串和 3 个整数的组合。 如果我写 cin >> (string) s >> (int) a >> (int) b >> (int) c; 我的程序将在我写一个字符串时立即停止,只有 2整数。有什么方法可以更改程序的这一部分吗?

示例输入:

sum 2 3
sub 5 3 
sum 1 5 6
sum 2 5 6
sub 1 7 

最佳答案

  1. 逐行读取输入。
  2. 使用 std::istringstream 处理每一行以产生所需的输出。

std::string line;
while ( getline(std::cin, line) )
{
    std::istringstring str(line)

    std::string token;
    if ( str >> token )
    {
        std::cout << "string ";
    }

    int n;
    while ( str >> n )
    {
        std::cout << "int ";
    }
}

关于c++ - 如何接受可变数量的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331746/

相关文章:

c++ - 递归正则表达式与boost匹配

c++ - 图的平均最优路径

c++ - 统一码计数器C/C++计数规则

c++ - 在 OpenGL C++ 中绘制一个球和两个圆锥体

c++ - GetWindowThreadProcessId 找不到我的窗口句柄,即使它的进程 ID 存在于 Window 上

c++ - 如何在cpp中访问 parent 的运营商

c++ - Qt C++ QRegExp 解析字符串

c++ - 结构类似于优先级队列,但具有类似下限的结构

c++ - 多个 operator[] 重载

c++ - 从最小化的窗口捕获图像