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

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

本文关键字:std cin Dummy 替换      更新时间:2023-10-16

给定下面的简单程序:

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;
}

但是,当然,该代码不起作用。我是否可以做些什么来允许我将数据"管道"到std::cin中,而无需像echo "1 2 3 4 5 6 7 8 9 10" | myprogram.exe那样手动从其他程序或命令行 shell 管道输入数据

您可以操纵与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 工作。