我有一个文件,我希望我的程序使用来自命令行的输入重定向来读取该文件。例如,a.out < file.dat
.然后我打算使用 cin.get()
并将字符放入数组中。
我不想对任何输入文件名进行硬编码,我已经在一些现有帖子中看到过这种情况。如果我将此输入重定向视为 stdin
,我必须明确打开我的文件吗?
int main (int argc, char *argv[])
{
string filename;
ifstream infile;
cin >> filename;
do {
int c = 0;
c = infile.get(); //need to get one character at a time
//further process
} while ( ! infile.eof());
最佳答案
你可以只使用cin
,这是与 stdin
#include <iostream>
int main()
{
char c;
while (std::cin.get(c))
{
std::cout << c << std::endl; // will print out each character on a new line
}
exit(0);
}
关于c++ - 使用输入重定向,如何在C中读取文件并获取字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13559462/