如何将"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;
}
但是,当然,该代码不起作用。我是否可以做些什么来允许我将数据"管道"到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 工作。
相关文章:
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- Problems with std::cin.fail()
- istream std::cin如何修改自定义istream缓冲区
- 在 std::getline 和 std::cin 期间卡在循环中
- C++ 限制或使用户输入不可见 (std::cin)
- 吃完 EOF 后重复使用 std::cin
- 当使用 std::CIN 输入结构时,它会出错
- 如何使 std::istream 从键盘获取输入(如 std::cin)?
- 如何将 std::cin 作为函数的参数传递?
- std::cin不接受输入
- 在C++中使用 std::cin 将字符传递给 int
- 为什么 std::cin 从一开始就不读
- 从 R 控制台获取用户输入:Rcpp 和 std::cin
- 定义宏时与 std::cin C++中的分段错误
- 如何终止 std::cin.get() 的 ''
- 将 istream 转换为 ifstream 时将 std::cin 传递到参数时出现问题
- STD :: cin和Scanf()应用于字符串之间的区别
- 在GLFW应用程序中,std::cin的行为很奇怪
- 如何使用std::cin函数后修复从文件读取的问题
- std::string 是否仅适用于 c++ 中的'std::cin'