2016-11-28 17 views
-1

想象一下下面的命令:C++ - 运行时,检索从尖括号数据文件

./functions < file.txt 

在我从functions.cpp的main(),我怎么能赶上通过“<”给出的数据?

我很确定我必须使用std::cin但除了提示用户输入信息之外,我不知道如何在这里应用。

std::string file_passed; 
std::cin >> file_passed; // prompts user 
file_passed << std::cin; // error 

这是一个noob问题,但我无法找到答案任何地方......谢谢。

+0

'给std :: cin >> file_passed'不会提示任何用户。如果一个文件被传入STDIN,'std :: cin'将读取文件数据。如果你想知道STDIN是否是管道输入与用户输入,你必须使用平台特定的API来查询控制台的信息。请参阅http://stackoverflow.com/questions/1312922/,http://stackoverflow.com/questions/6839508/,等 –

回答

2

这是你如何让通过命令行重定向输入:

std::string temp; 
// will read each word in the file in the variable temp on each loop iteration until EOF 
while (std::cin >> temp) 
{   
    // you use temp here 
    std::cout << temp << std::endl; 
} 
+0

这个问题来自我对管道参数的误解..认为做<文件是给文件和不是它的内容。 正如我然后试图做fstream stream - > stream.open(文件),并无法打开它... 感谢您打开我的眼睛在这个问题上。 – TryingLikeICan