在c++中使用unix shell中的文本文件时,如何请求用户输入

How can you ask for user input when also using a text file in unix shell in c++?

本文关键字:何请求 输入 用户 请求 文件 c++ unix shell 文本      更新时间:2023-10-16

我使用a.out < file.txt运行代码,当我尝试使用cin >> variable请求用户输入时,我读取了所有文件,但它什么也没做。

当您用a.out < file.txt调用程序时,您要求shell将file.txt内容作为a.out的标准输入,而不是让键盘提供标准输入。如果这不适合你,那么添加一个命令行参数来指定文件名,使用ifstream打开文件名并从中读取,而不是使用cin,或者使用cin作为键盘输入。

例如:

int main(int argc, const char* argv[])
{
    if (argc != 2)
    {
        std::cerr << "usage: " << argv[0] << " <filename>n";
        exit(1);
    }
    const char* filename = argv[1];
    if (std::ifstream in(filename))
    {
        // process the file content, e.g.
        std::string line;
        while (getline(in, line))
            std::cout << "read '" << line << "'n";
    }
    else
    {
        std::cerr << "unable to open "" << filename << ""n";
        exit(1);
    }
    // can still read from std::cin down here...
}

如果在stdin之后需要额外的用户输入,则必须打开名为"/dev/tty"的控制终端。示例:

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
  ifstream tin("/dev/tty");
  ofstream tout("/dev/tty");
  tin.tie(&tout);
  while (true) {
    string input;
    tout << "> ";
    getline(tin, input);
    if (input == "quit")
      break;
  }
  return 0;
}

为了说服自己,上面不会读取重定向文件,一个简单的测试:

$ echo "quit" | ./a.out
>