C++ “如何替换”;“哑巴”;std::cin的值?

C++ “如何替换”;“哑巴”;std::cin的值?,c++,iostream,cin,C++,Iostream,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::

根据下面的简单程序:

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
中,而不必手动从其他程序或命令行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;
}
#包括
#包括
#包括

#包括。

如果可能,将
std::cin
更改为
std::istringstream
对象会起作用。函数将使用
std::istream&
参数,而不是直接使用
std::cin
#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;
}