以下示例输出来自stdin
的输入:
#include <iostream>
int main(int argc, char **argv)
{
std::string s1, s2;
while (getline(std::cin, s1))
{
std::cout << s1 << " 1\n";
}
while (getline(std::cin, s2))
{
std::cout << s2 << "2\n";
}
return 0;
}
我运行这样的程序:cat main.cpp | ./main
输出
#include <iostream> 1
1
int main(int argc, char **argv) 1
{ 1
1
std::string s1, s2; 1
while (getline(std::cin, s1)) 1
{ 1
std::cout << s1 << " 1\n"; 1
} 1
1
while (getline(std::cin, s2)) 1
{ 1
std::cout << s2 << "2\n"; 1
} 1
} 1
有没有办法通过stdin
将两个单独的输入传递给程序?即,如果我写了类似cat main.cpp cat main.cpp | ./main
的内容,那么第一个输入会被分配到s1
而第二个输入被分配到s2
?
答案 0 :(得分:4)
AFAIK这是不可能的,但您可以简单地使用包含输入的两个文件,将它们作为命令行参数传递并从中读取。
#include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
if (argc != 3)
return -1;
std::ifstream ifs1(argv[1]);
std::ifstream ifs2(argv[2]);
if (!ifs1.is_open() || !ifs2.is_open())
return -2;
std::string s1, s2;
while (getline(ifs1, s1))
{
std::cout << s1 << " 1\n";
}
while (getline(ifs2, s2))
{
std::cout << s2 << "2\n";
}
return 0;
}
并称之为:
./main main.cpp main.cpp
您甚至可以使其更灵活,允许您阅读任意数量的文件:
#include <iostream>
#include <fstream>
int main(int argc, char **argv)
{
if (argc == 1)
return -1; // no input file given
for (int i = 1; i < argc; ++i) {
std::ifstream ifs(argv[i]);
if (!ifs.is_open()) {
std::cout << argv[i] << ":file not found\n";
continue;
}
std::string line;
while (getline(ifs, line))
{
std::cout << line << " " << i << "\n";
}
}
}
答案 1 :(得分:1)
function.json
没有在文件之间放置任何类型的分隔符,因此管道另一端的程序无法知道一个文件的结束位置和下一个文件的开始位置。你可以自己做,比如:
{
"bindings": [
{
"name": "imageStream",
"type": "blobTrigger",
"direction": "in",
"path": "input-container/{imageName}.{extension}",
"connection": "AzureWebJobsDashboard"
},
{
"type": "blob",
"name": "outputBlob",
"path": "output-container/{imageName}.jpg",
"connection": "AzureWebJobsDashboard",
"direction": "inout"
}
],
"disabled": false
}
并更改程序以查找cat
行:
{ cat main.cpp; echo "**END**"; cat main.cpp; } | ./main