如何将 "Dummy" 值替换为 std::cin?

How to Substitute "Dummy" values to std::cin?

给出下面的简单程序:

int main() {
    int v;
    std::vector<int> values;
    while(std::cin >> v) {
        values.emplace_back(v);
    }
    std::cout << "The Sum is " << std::accumulate(values.begin(), values.end(), 0) << std::endl;
    return 0;
}

我想在执行此代码之前以编程方式填写 std::cin,方式类似于以下内容:

int main() {
    int v;
    std::vector<int> values;
    for(int i = 0; i < 10; i++) {
        std::cin << i << " "; //Doesn't compile, obviously
    }
    /*
    The Rest of the Code.
    */
    return 0;
}

当然,该代码不起作用。有什么我可以做的,可以让我 "pipe" 数据进入 std::cin 而无需手动从其他程序或命令行输入数据 shell 喜欢 echo "1 2 3 4 5 6 7 8 9 10" | myprogram.exe 吗?

您可以操纵与 std::cin 关联的 rdbuf 来实现它。

#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>

int main() {
   int v;
   std::vector<int> values;

   // Create a istringstream using a hard coded string.
   std::string data = "10 15 20";
   std::istringstream str(data);

   // Use the rdbuf of the istringstream as the rdbuf of std::cin.
   auto old = std::cin.rdbuf(str.rdbuf());

   while(std::cin >> v) {
      values.emplace_back(v);
   }
   std::cout << "The Sum is " << std::accumulate(values.begin(), values.end(), 0) << std::endl;

   // Restore the rdbuf of std::cin.
   std::cin.rdbuf(old);

   return 0;
}

查看它在 http://ideone.com/ZF02op 的工作情况。