C++ 从命令行c++;
我想用两种方式运行代码和发送文件C++ 从命令行c++;,c++,file,c++11,command-line,C++,File,C++11,Command Line,我想用两种方式运行代码和发送文件 myprogram具有将格式化文本读入某种二进制表示的优点 C型IO的优点是能够很好地读取二进制数据 这取决于您想用它做什么您想从stdin读取的输入,为此有两个选项: std::cin fread()和其他C风格IO std::cin>具有将格式化文本读入某种二进制表示的优点 C型IO的优点是能够很好地读取二进制数据 这取决于您想对输入执行什么操作如上所述,一种可移植的方法是将打开的文件或std::cin作为istream引用传递到函数并在那里输入。在这种
myprogram
或cat input.txt|myprogram
myprogram input.txt
argc
和argv[]
找到了secong方法,但我无法找到如何编写第一个选项的代码
int main (int argc, char *argv[])
{
ifstream fin;
if(argc > 1){
fin.open (argv[1]);
}
else
}
您想从stdin中读取,为此有两个选项:
std::cin
和其他C风格IOfread()
std::cin>
具有将格式化文本读入某种二进制表示的优点
C型IO的优点是能够很好地读取二进制数据
这取决于您想用它做什么您想从stdin读取的输入,为此有两个选项:
std::cin
和其他C风格IOfread()
std::cin>
具有将格式化文本读入某种二进制表示的优点
C型IO的优点是能够很好地读取二进制数据
这取决于您想对输入执行什么操作如上所述,一种可移植的方法是将打开的文件或
std::cin
作为istream
引用传递到函数并在那里输入。在这种情况下,可以传递文件或std::cin
。例如
#include <iostream>
#include <fstream>
#include <string>
void readinfo (std::istream& in)
{
std::string s;
while (in >> s)
std::cout << s << '\n';
}
int main (int argc, char **argv) {
if (argc > 1) { /* read from file if given as argument */
std::ifstream fin (argv[1]);
if (fin.is_open())
readinfo (fin);
else {
std::cerr << "error: file open failed.\n";
return 1;
}
}
else { /* read from stdin */
readinfo (std::cin);
}
return 0;
}
两者都不完美,但都支持(受操作系统限制)
如上所述,一种可移植的方法是将打开的文件或
std::cin
作为istream
引用传递到函数,并在其中进行输入。在这种情况下,可以传递文件或std::cin
。例如
#include <iostream>
#include <fstream>
#include <string>
void readinfo (std::istream& in)
{
std::string s;
while (in >> s)
std::cout << s << '\n';
}
int main (int argc, char **argv) {
if (argc > 1) { /* read from file if given as argument */
std::ifstream fin (argv[1]);
if (fin.is_open())
readinfo (fin);
else {
std::cerr << "error: file open failed.\n";
return 1;
}
}
else { /* read from stdin */
readinfo (std::cin);
}
return 0;
}
两者都不完美,但都支持(受操作系统限制)
您的意思是要在代码中使用管道操作符吗?或者您正在询问如何使用>运算符写入input.txt?你的意思是
myprogram
和myprogram input.txt
。使用myprogram>input.txt
写入input.txt
Yes myprogram“/dev/stdin”
。可移植解决方案需要将std::cin
作为istream
引用传递,如果没有给出参数,则需要在函数中读取。您的意思是想在代码中使用管道操作符吗?或者您正在询问如何使用>运算符写入input.txt?你的意思是myprogram
和myprogram input.txt
。使用myprogram>input.txt
写入input.txt
Yes myprogram“/dev/stdin”
。一个可移植的解决方案需要将std::cin
作为istream
引用传递,如果没有给出参数,则需要在函数中读取。在else块{cin>>s;fin.open(s)}中,这就是您的意思吗?因此stdin已经是一个文件,因此您不需要打开它,您可以从中读取。基本上有两种方法。C++方式是使用STD::Cix:Cuff< <代码> FRADE< /COD>(和<代码> FETGS ,myprogram
,然后接受Davids的答案。明白了!非常感谢你,很高兴它起了作用。祝您编码顺利。@KumudaAggarwal您应该将原始问题更改为myprogram
,然后接受Davids的答案。
myprogram < input.txt
myprogram input.txt