假设我有一个包含一些命令的 main() 函数, 例如
int main()
{
ofstream myfile;
while(!cin.eof()){
string command; string word;
cin >> command;
cin >> word;
if (command.compare("add") == 0) {
//do Something
}
if (command.compare("use") == 0){
myfile.open(word);
myfile >> //loop back into this loop as stdin
myfile.close();
}
}
myfile 的内容将为文件中的每一行都有一个“命令”“单词”字段。我想知道是否有一种方法可以将文件作为输入读取并将其循环回 main() 循环?
最佳答案
拆分工作:
#include <string>
#include <iostream>
void process(std::istream & is)
{
for (std::string command, word; is >> command >> word; )
{
if (command == "add") { /* ... */ continue; }
if (command == "include")
{
std::ifstream f(word); // or "f(word.c_str())" pre-C++11
if (!f) { /* error opening file! */ }
process(f);
continue;
}
// ...
}
}
int main()
{
process(std::cin);
}
关于c++ - 作为标准输入从文件中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993621/